From 67ff0fc78b2933b8b4f5a8544c7639499824e622 Mon Sep 17 00:00:00 2001 From: Tom Pantelis Date: Wed, 26 Oct 2016 08:25:33 -0400 Subject: [PATCH] Fix CS warnings in blueprint and enable enforcement Fixed checkstyle warnings and enabled enforcement. Most of the warnings/changes were for: - white space before if/for/while/catch - variable name too short - line too long - illegal catching of Exception Change-Id: I2a9eb1dc47f46a2c56dc2415ee9ebb73ec7d18c4 Signed-off-by: Tom Pantelis --- opendaylight/blueprint/pom.xml | 7 ++ .../blueprint/BlueprintBundleTracker.java | 68 +++++------ .../BlueprintContainerRestartServiceImpl.java | 84 ++++++-------- ...ractDependentComponentFactoryMetadata.java | 37 +++--- .../blueprint/ext/ComponentProcessor.java | 28 ++--- .../ext/DataStoreAppConfigMetadata.java | 108 +++++++++--------- .../ext/NotificationListenerBean.java | 3 +- .../ext/OpendaylightNamespaceHandler.java | 96 ++++++++-------- .../blueprint/ext/RoutedRpcMetadata.java | 20 ++-- .../ext/RoutedRpcRegistrationConverter.java | 4 +- .../blueprint/ext/RpcImplementationBean.java | 19 +-- .../blueprint/ext/RpcServiceMetadata.java | 27 +++-- .../ext/SpecificReferenceListMetadata.java | 38 +++--- .../ext/StaticServiceReferenceRecipe.java | 22 ++-- .../blueprint/ext/UpdateStrategy.java | 2 +- 15 files changed, 284 insertions(+), 279 deletions(-) diff --git a/opendaylight/blueprint/pom.xml b/opendaylight/blueprint/pom.xml index 649fed5c66..226a03774c 100644 --- a/opendaylight/blueprint/pom.xml +++ b/opendaylight/blueprint/pom.xml @@ -96,6 +96,13 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle.violationSeverity=error + + diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/BlueprintBundleTracker.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/BlueprintBundleTracker.java index ed416c5fb4..6c267ac5fe 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/BlueprintBundleTracker.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/BlueprintBundleTracker.java @@ -11,7 +11,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashSet; @@ -146,7 +145,7 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus public void bundleChanged(BundleEvent event) { // If the system bundle (id 0) is stopping, do an orderly shutdown of all blueprint containers. On // shutdown the system bundle is stopped first. - if(event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) { + if (event.getBundle().getBundleId() == SYSTEM_BUNDLE_ID && event.getType() == BundleEvent.STOPPING) { shutdownAllContainers(); } } @@ -165,14 +164,14 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus */ @Override public void modifiedBundle(Bundle bundle, BundleEvent event, Bundle object) { - if(shuttingDown) { + if (shuttingDown) { return; } - if(bundle.getState() == Bundle.ACTIVE) { + if (bundle.getState() == Bundle.ACTIVE) { List paths = findBlueprintPaths(bundle); - if(!paths.isEmpty()) { + if (!paths.isEmpty()) { LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths); blueprintExtenderService.createContainer(bundle, paths); @@ -191,23 +190,23 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus /** * Implemented from EventHandler to listen for blueprint events. * - * @param event + * @param event the event to handle */ @Override public void handleEvent(Event event) { - if(EventConstants.TOPIC_CREATED.equals(event.getTopic())) { + if (EventConstants.TOPIC_CREATED.equals(event.getTopic())) { LOG.info("Blueprint container for bundle {} was successfully created", event.getProperty(EventConstants.BUNDLE)); - } else if(EventConstants.TOPIC_FAILURE.equals(event.getTopic())) { + } else if (EventConstants.TOPIC_FAILURE.equals(event.getTopic())) { // If the container timed out waiting for dependencies, we'll destroy it and start it again. This // is indicated via a non-null DEPENDENCIES property containing the missing dependencies. The // default timeout is 5 min and ideally we would set this to infinite but the timeout can only // be set at the bundle level in the manifest - there's no way to set it globally. - if(event.getProperty(EventConstants.DEPENDENCIES) != null) { + if (event.getProperty(EventConstants.DEPENDENCIES) != null) { Bundle bundle = (Bundle) event.getProperty(EventConstants.BUNDLE); List paths = findBlueprintPaths(bundle); - if(!paths.isEmpty()) { + if (!paths.isEmpty()) { LOG.warn("Blueprint container for bundle {} timed out waiting for dependencies - restarting it", event.getProperty(EventConstants.BUNDLE)); @@ -219,11 +218,11 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus @SuppressWarnings({ "rawtypes", "unchecked" }) static List findBlueprintPaths(Bundle bundle) { - Enumeration e = bundle.findEntries(BLUEPRINT_FILE_PATH, BLUEPRINT_FLE_PATTERN, false); - if(e == null) { + Enumeration rntries = bundle.findEntries(BLUEPRINT_FILE_PATH, BLUEPRINT_FLE_PATTERN, false); + if (rntries == null) { return Collections.emptyList(); } else { - return Collections.list((Enumeration)e); + return Collections.list((Enumeration)rntries); } } @@ -234,20 +233,20 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus // Close all CSS modules first. ConfigSystemService configSystem = getOSGiService(ConfigSystemService.class); - if(configSystem != null) { + if (configSystem != null) { configSystem.closeAllConfigModules(); } LOG.info("Shutting down all blueprint containers..."); Collection containerBundles = new HashSet<>(Arrays.asList(bundleContext.getBundles())); - while(!containerBundles.isEmpty()) { + while (!containerBundles.isEmpty()) { // For each iteration of getBundlesToDestroy, as containers are destroyed, other containers become // eligible to be destroyed. We loop until we've destroyed them all. - for(Bundle bundle : getBundlesToDestroy(containerBundles)) { + for (Bundle bundle : getBundlesToDestroy(containerBundles)) { containerBundles.remove(bundle); BlueprintContainer container = blueprintExtenderService.getContainer(bundle); - if(container != null) { + if (container != null) { blueprintExtenderService.destroyContainer(bundle, container); } } @@ -261,28 +260,23 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus // Find all container bundles that either have no registered services or whose services are no // longer in use. - for(Bundle bundle : containerBundles) { + for (Bundle bundle : containerBundles) { ServiceReference[] references = bundle.getRegisteredServices(); int usage = 0; - if(references != null) { - for(ServiceReference reference : references) { + if (references != null) { + for (ServiceReference reference : references) { usage += getServiceUsage(reference); } } LOG.debug("Usage for bundle {} is {}", bundle, usage); - if(usage == 0) { + if (usage == 0) { bundlesToDestroy.add(bundle); } } - if(!bundlesToDestroy.isEmpty()) { - Collections.sort(bundlesToDestroy, new Comparator() { - @Override - public int compare(Bundle b1, Bundle b2) { - return (int) (b2.getLastModified() - b1.getLastModified()); - } - }); + if (!bundlesToDestroy.isEmpty()) { + Collections.sort(bundlesToDestroy, (b1, b2) -> (int) (b2.getLastModified() - b1.getLastModified())); LOG.debug("Selected bundles {} for destroy (no services in use)", bundlesToDestroy); } else { @@ -295,30 +289,30 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus // is likely the safest to destroy at this point. ServiceReference ref = null; - for(Bundle bundle : containerBundles) { + for (Bundle bundle : containerBundles) { ServiceReference[] references = bundle.getRegisteredServices(); - if(references == null) { + if (references == null) { continue; } - for(ServiceReference reference : references) { + for (ServiceReference reference : references) { // We did check the service usage above but it's possible the usage has changed since // then, - if(getServiceUsage(reference) == 0) { + if (getServiceUsage(reference) == 0) { continue; } // Choose 'reference' if it has a lower service ranking or, if the rankings are equal // which is usually the case, if it has a higher service ID. For the latter the < 0 // check looks backwards but that's how ServiceReference#compareTo is documented to work. - if(ref == null || reference.compareTo(ref) < 0) { + if (ref == null || reference.compareTo(ref) < 0) { LOG.debug("Currently selecting bundle {} for destroy (with reference {})", bundle, reference); ref = reference; } } } - if(ref != null) { + if (ref != null) { bundlesToDestroy.add(ref.getBundle()); } @@ -337,19 +331,19 @@ public class BlueprintBundleTracker implements BundleActivator, BundleTrackerCus private T getOSGiService(Class serviceInterface) { try { ServiceReference serviceReference = bundleContext.getServiceReference(serviceInterface); - if(serviceReference == null) { + if (serviceReference == null) { LOG.warn("{} service reference not found", serviceInterface.getSimpleName()); return null; } T service = bundleContext.getService(serviceReference); - if(service == null) { + if (service == null) { // This could happen on shutdown if the service was already unregistered so we log as debug. LOG.debug("{} service instance was not found", serviceInterface.getSimpleName()); } return service; - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we // log as debug. LOG.debug("Error obtaining OSGi service {}", serviceInterface.getSimpleName(), e); diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/BlueprintContainerRestartServiceImpl.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/BlueprintContainerRestartServiceImpl.java index 02b7bac1b7..6a464b75d0 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/BlueprintContainerRestartServiceImpl.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/BlueprintContainerRestartServiceImpl.java @@ -49,7 +49,6 @@ import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.framework.ServiceRegistration; import org.osgi.service.blueprint.container.EventConstants; -import org.osgi.service.event.Event; import org.osgi.service.event.EventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -67,8 +66,8 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo private static final String CONFIG_MODULE_NAME_PROP = "config-module-name"; private static final String CONFIG_INSTANCE_NAME_PROP = "config-instance-name"; - private final ExecutorService restartExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder(). - setDaemon(true).setNameFormat("BlueprintContainerRestartService").build()); + private final ExecutorService restartExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder() + .setDaemon(true).setNameFormat("BlueprintContainerRestartService").build()); private final BlueprintExtenderService blueprintExtenderService; BlueprintContainerRestartServiceImpl(BlueprintExtenderService blueprintExtenderService) { @@ -76,36 +75,27 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo } public void restartContainer(final Bundle bundle, final List paths) { - if(restartExecutor.isShutdown()) { + if (restartExecutor.isShutdown()) { return; } LOG.debug("restartContainer for bundle {}", bundle); - restartExecutor.execute(new Runnable() { - @Override - public void run() { - blueprintExtenderService.destroyContainer(bundle, blueprintExtenderService.getContainer(bundle)); - blueprintExtenderService.createContainer(bundle, paths); - } + restartExecutor.execute(() -> { + blueprintExtenderService.destroyContainer(bundle, blueprintExtenderService.getContainer(bundle)); + blueprintExtenderService.createContainer(bundle, paths); }); } @Override public void restartContainerAndDependents(final Bundle bundle) { - if(restartExecutor.isShutdown()) { + if (restartExecutor.isShutdown()) { return; } LOG.debug("restartContainerAndDependents for bundle {}", bundle); - restartExecutor.execute(new Runnable() { - @Override - public void run() { - restartContainerAndDependentsInternal(bundle); - - } - }); + restartExecutor.execute(() -> restartContainerAndDependentsInternal(bundle)); } private void restartContainerAndDependentsInternal(Bundle forBundle) { @@ -120,7 +110,7 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo containerBundles.subList(1, containerBundles.size())); // Destroy the containers in reverse order with 'forBundle' last, ie bottom-up in the service tree. - for(Bundle bundle: Lists.reverse(containerBundles)) { + for (Bundle bundle: Lists.reverse(containerBundles)) { blueprintExtenderService.destroyContainer(bundle, blueprintExtenderService.getContainer(bundle)); } @@ -129,18 +119,15 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo // containers are complete. This is done to ensure all blueprint containers are finished before we // restart config modules. final CountDownLatch containerCreationComplete = new CountDownLatch(containerBundles.size()); - ServiceRegistration eventHandlerReg = registerEventHandler(forBundle.getBundleContext(), new EventHandler() { - @Override - public void handleEvent(Event event) { - LOG.debug("handleEvent {} for bundle {}", event.getTopic(), event.getProperty(EventConstants.BUNDLE)); - if(containerBundles.contains(event.getProperty(EventConstants.BUNDLE))) { - containerCreationComplete.countDown(); - } + ServiceRegistration eventHandlerReg = registerEventHandler(forBundle.getBundleContext(), event -> { + LOG.debug("handleEvent {} for bundle {}", event.getTopic(), event.getProperty(EventConstants.BUNDLE)); + if (containerBundles.contains(event.getProperty(EventConstants.BUNDLE))) { + containerCreationComplete.countDown(); } }); // Restart the containers top-down starting with 'forBundle'. - for(Bundle bundle: containerBundles) { + for (Bundle bundle: containerBundles) { List paths = BlueprintBundleTracker.findBlueprintPaths(bundle); LOG.info("Restarting blueprint container for bundle {} with paths {}", bundle, paths); @@ -150,7 +137,7 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo try { containerCreationComplete.await(5, TimeUnit.MINUTES); - } catch(InterruptedException e) { + } catch (InterruptedException e) { LOG.debug("CountDownLatch await was interrupted - returning"); return; } @@ -161,20 +148,21 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo restartConfigModules(forBundle.getBundleContext(), configModules); } - private void restartConfigModules(BundleContext bundleContext, List> configModules) { - if(configModules.isEmpty()) { + private void restartConfigModules(BundleContext bundleContext, List> configModules) { + if (configModules.isEmpty()) { return; } - ServiceReference configFacadeFactoryRef = - bundleContext.getServiceReference(ConfigSubsystemFacadeFactory.class); - if(configFacadeFactoryRef == null) { + ServiceReference configFacadeFactoryRef = bundleContext + .getServiceReference(ConfigSubsystemFacadeFactory.class); + if (configFacadeFactoryRef == null) { LOG.debug("ConfigSubsystemFacadeFactory service reference not found"); return; } ConfigSubsystemFacadeFactory configFacadeFactory = bundleContext.getService(configFacadeFactoryRef); - if(configFacadeFactory == null) { + if (configFacadeFactory == null) { LOG.debug("ConfigSubsystemFacadeFactory service not found"); return; } @@ -182,7 +170,8 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo ConfigSubsystemFacade configFacade = configFacadeFactory.createFacade("BlueprintContainerRestartService"); try { restartConfigModules(configModules, configFacade); - } catch(Exception e) { + } catch (ParserConfigurationException | DocumentedException | ValidationException + | ConflictingVersionException e) { LOG.error("Error restarting config modules", e); } finally { configFacade.close(); @@ -204,7 +193,7 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo Config configMapping = configFacade.getConfigMapping(); ConfigRegistry configRegistryClient = new ConfigRegistryJMXClient(ManagementFactory.getPlatformMBeanServer()); - for(Entry entry: configModules) { + for (Entry entry: configModules) { String moduleNamespace = entry.getKey(); ModuleIdentifier moduleId = entry.getValue(); try { @@ -216,13 +205,13 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo Element moduleElement = configMapping.moduleToXml(moduleNamespace, moduleId.getFactoryName(), moduleId.getInstanceName(), instanceON, document); modulesElement.appendChild(moduleElement); - } catch(InstanceNotFoundException e) { + } catch (InstanceNotFoundException e) { LOG.warn("Error looking up config module: namespace {}, module name {}, instance {}", moduleNamespace, moduleId.getFactoryName(), moduleId.getInstanceName(), e); } } - if(LOG.isDebugEnabled()) { + if (LOG.isDebugEnabled()) { LOG.debug("Pushing config xml: {}", XmlUtil.toString(dataElement)); } @@ -243,7 +232,7 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo */ private void findDependentContainersRecursively(Bundle bundle, Set containerBundles, List> configModules) { - if(!containerBundles.add(bundle)) { + if (!containerBundles.add(bundle)) { // Already seen this bundle... return; } @@ -254,9 +243,9 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo possiblyAddConfigModuleIdentifier(reference, configModules); Bundle[] usingBundles = reference.getUsingBundles(); - if(usingBundles != null) { - for(Bundle usingBundle: usingBundles) { - if(blueprintExtenderService.getContainer(usingBundle) != null) { + if (usingBundles != null) { + for (Bundle usingBundle : usingBundles) { + if (blueprintExtenderService.getContainer(usingBundle) != null) { findDependentContainersRecursively(usingBundle, containerBundles, configModules); } } @@ -268,7 +257,7 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo private void possiblyAddConfigModuleIdentifier(ServiceReference reference, List> configModules) { Object moduleNamespace = reference.getProperty(CONFIG_MODULE_NAMESPACE_PROP); - if(moduleNamespace == null) { + if (moduleNamespace == null) { return; } @@ -276,7 +265,7 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo reference); String instanceName = getRequiredConfigModuleProperty(CONFIG_INSTANCE_NAME_PROP, moduleNamespace, reference); - if(moduleName == null || instanceName == null) { + if (moduleName == null || instanceName == null) { return; } @@ -291,9 +280,10 @@ class BlueprintContainerRestartServiceImpl implements AutoCloseable, BlueprintCo private String getRequiredConfigModuleProperty(String propName, Object moduleNamespace, ServiceReference reference) { Object value = reference.getProperty(propName); - if(value == null) { - LOG.warn("OSGi service with {} property is missing property {} therefore the config module can't be restarted", - CONFIG_MODULE_NAMESPACE_PROP, propName); + if (value == null) { + LOG.warn( + "OSGi service with {} property is missing property {} therefore the config module can't be restarted", + CONFIG_MODULE_NAMESPACE_PROP, propName); return null; } diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/AbstractDependentComponentFactoryMetadata.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/AbstractDependentComponentFactoryMetadata.java index 8001c3e4d6..c55fa0ce91 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/AbstractDependentComponentFactoryMetadata.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/AbstractDependentComponentFactoryMetadata.java @@ -26,6 +26,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** + * Abstract base class for a DependentComponentFactoryMetadata implementation. + * * @author Thomas Pantelis */ abstract class AbstractDependentComponentFactoryMetadata implements DependentComponentFactoryMetadata { @@ -70,8 +72,6 @@ abstract class AbstractDependentComponentFactoryMetadata implements DependentCom return satisfied.get(); } - protected abstract void startTracking(); - protected void setFailureMessage(String failureMessage) { setFailure(failureMessage, null); } @@ -90,7 +90,7 @@ abstract class AbstractDependentComponentFactoryMetadata implements DependentCom } protected void setSatisfied() { - if(satisfied.compareAndSet(false, true)) { + if (satisfied.compareAndSet(false, true)) { satisfactionCallback.notifyChanged(); } } @@ -109,19 +109,18 @@ abstract class AbstractDependentComponentFactoryMetadata implements DependentCom } protected final String logName() { - return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + - " (" + id + ")"; + return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + " (" + id + ")"; } @Override - public void init(ExtendedBlueprintContainer container) { - this.container = container; + public void init(ExtendedBlueprintContainer newContainer) { + this.container = newContainer; log.debug("{}: In init", logName()); } protected void onCreate() throws ComponentDefinitionException { - if(failureMessage != null) { + if (failureMessage != null) { throw new ComponentDefinitionException(failureMessage, failureCause); } @@ -152,7 +151,7 @@ abstract class AbstractDependentComponentFactoryMetadata implements DependentCom executionContext.removePartialObject(id); Recipe myRecipe = executionContext.getRecipe(id); - if(myRecipe instanceof AbstractRecipe) { + if (myRecipe instanceof AbstractRecipe) { log.debug("{}: setPrototype to false", logName()); ((AbstractRecipe)myRecipe).setPrototype(false); } else { @@ -160,15 +159,17 @@ abstract class AbstractDependentComponentFactoryMetadata implements DependentCom } } + protected abstract void startTracking(); + @Override - public final void startTracking(final SatisfactionCallback satisfactionCallback) { - if(!started.compareAndSet(false, true)) { + public final void startTracking(final SatisfactionCallback newSatisfactionCallback) { + if (!started.compareAndSet(false, true)) { return; } log.debug("{}: In startTracking", logName()); - this.satisfactionCallback = satisfactionCallback; + this.satisfactionCallback = newSatisfactionCallback; startTracking(); } @@ -188,7 +189,7 @@ abstract class AbstractDependentComponentFactoryMetadata implements DependentCom } private void stopServiceRecipes() { - for(StaticServiceReferenceRecipe recipe: serviceRecipes) { + for (StaticServiceReferenceRecipe recipe: serviceRecipes) { recipe.stop(); } @@ -196,9 +197,9 @@ abstract class AbstractDependentComponentFactoryMetadata implements DependentCom } protected void restartContainer() { - if(restarting.compareAndSet(false, true)) { + if (restarting.compareAndSet(false, true)) { BlueprintContainerRestartService restartService = getOSGiService(BlueprintContainerRestartService.class); - if(restartService != null) { + if (restartService != null) { log.debug("{}: Restarting container", logName()); restartService.restartContainerAndDependents(container().getBundleContext().getBundle()); } @@ -211,19 +212,19 @@ abstract class AbstractDependentComponentFactoryMetadata implements DependentCom try { ServiceReference serviceReference = container().getBundleContext().getServiceReference(serviceInterface); - if(serviceReference == null) { + if (serviceReference == null) { log.warn("{}: {} reference not found", logName(), serviceInterface.getSimpleName()); return null; } T service = (T)container().getService(serviceReference); - if(service == null) { + if (service == null) { // This could happen on shutdown if the service was already unregistered so we log as debug. log.debug("{}: {} was not found", logName(), serviceInterface.getSimpleName()); } return service; - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { // This is thrown if the BundleContext is no longer valid which is possible on shutdown so we // log as debug. log.debug("{}: Error obtaining {}", logName(), serviceInterface.getSimpleName(), e); diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/ComponentProcessor.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/ComponentProcessor.java index 5daa6e4f38..14b3c2b849 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/ComponentProcessor.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/ComponentProcessor.java @@ -64,7 +64,7 @@ public class ComponentProcessor implements ComponentDefinitionRegistryProcessor } public void destroy() { - for(ServiceRegistration reg: managedServiceRegs) { + for (ServiceRegistration reg: managedServiceRegs) { AriesFrameworkUtil.safeUnregisterService(reg); } } @@ -73,18 +73,18 @@ public class ComponentProcessor implements ComponentDefinitionRegistryProcessor public void process(ComponentDefinitionRegistry registry) { LOG.debug("{}: In process", logName()); - for(String name : registry.getComponentDefinitionNames()) { + for (String name : registry.getComponentDefinitionNames()) { ComponentMetadata component = registry.getComponentDefinition(name); - if(component instanceof MutableBeanMetadata) { - processMutableBeanMetadata((MutableBeanMetadata)component); - } else if(component instanceof MutableServiceReferenceMetadata) { + if (component instanceof MutableBeanMetadata) { + processMutableBeanMetadata((MutableBeanMetadata) component); + } else if (component instanceof MutableServiceReferenceMetadata) { processServiceReferenceMetadata((MutableServiceReferenceMetadata)component); } } } private void processServiceReferenceMetadata(MutableServiceReferenceMetadata serviceRef) { - if(!useDefaultForReferenceTypes) { + if (!useDefaultForReferenceTypes) { return; } @@ -95,7 +95,7 @@ public class ComponentProcessor implements ComponentDefinitionRegistryProcessor LOG.debug("{}: processServiceReferenceMetadata for {}, filter: {}, ext filter: {}", logName(), serviceRef.getId(), filter, extFilter); - if(Strings.isNullOrEmpty(filter) && Strings.isNullOrEmpty(extFilter)) { + if (Strings.isNullOrEmpty(filter) && Strings.isNullOrEmpty(extFilter)) { serviceRef.setFilter(DEFAULT_TYPE_FILTER); LOG.debug("{}: processServiceReferenceMetadata for {} set filter to {}", logName(), @@ -104,14 +104,14 @@ public class ComponentProcessor implements ComponentDefinitionRegistryProcessor } private void processMutableBeanMetadata(MutableBeanMetadata bean) { - if(restartDependentsOnUpdates && bean.getRuntimeClass() != null && - AbstractPropertyPlaceholder.class.isAssignableFrom(bean.getRuntimeClass())) { + if (restartDependentsOnUpdates && bean.getRuntimeClass() != null + && AbstractPropertyPlaceholder.class.isAssignableFrom(bean.getRuntimeClass())) { LOG.debug("{}: Found PropertyPlaceholder bean: {}, runtime {}", logName(), bean.getId(), bean.getRuntimeClass()); - for(BeanProperty prop: bean.getProperties()) { - if(CM_PERSISTENT_ID_PROPERTY.equals(prop.getName())) { - if(prop.getValue() instanceof ValueMetadata) { + for (BeanProperty prop : bean.getProperties()) { + if (CM_PERSISTENT_ID_PROPERTY.equals(prop.getName())) { + if (prop.getValue() instanceof ValueMetadata) { ValueMetadata persistentId = (ValueMetadata)prop.getValue(); LOG.debug("{}: Found {} property, value : {}", logName(), @@ -132,7 +132,7 @@ public class ComponentProcessor implements ComponentDefinitionRegistryProcessor private void registerManagedService(final String persistentId) { // Register a ManagedService so we get updates from the ConfigAdmin when the cfg file corresponding // to the persistentId changes. - ManagedService managedService = new ManagedService() { + final ManagedService managedService = new ManagedService() { private volatile boolean initialUpdate = true; @Override @@ -143,7 +143,7 @@ public class ComponentProcessor implements ComponentDefinitionRegistryProcessor // The first update occurs when the service is registered so ignore it as we want subsequent // updates when it changes. The ConfigAdmin will send an update even if the cfg file doesn't // yet exist. - if(initialUpdate) { + if (initialUpdate) { initialUpdate = false; } else { blueprintContainerRestartService.restartContainerAndDependents(bundle); diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/DataStoreAppConfigMetadata.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/DataStoreAppConfigMetadata.java index 73614971f3..b479d39ffe 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/DataStoreAppConfigMetadata.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/DataStoreAppConfigMetadata.java @@ -15,6 +15,8 @@ import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import java.io.File; import java.io.FileInputStream; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -23,6 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; import org.apache.aries.blueprint.services.ExtendedBlueprintContainer; import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener; import org.opendaylight.controller.md.sal.binding.api.DataBroker; @@ -34,7 +37,7 @@ import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; import org.opendaylight.controller.sal.core.api.model.SchemaService; -import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer; +import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer; import org.opendaylight.yangtools.concepts.ListenerRegistration; import org.opendaylight.yangtools.yang.binding.DataObject; import org.opendaylight.yangtools.yang.binding.Identifiable; @@ -57,6 +60,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; +import org.xml.sax.SAXException; /** * Factory metadata corresponding to the "clustered-app-config" element that obtains an application's @@ -74,9 +78,8 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor static final String DEFAULT_CONFIG_FILE_NAME = "default-config-file-name"; static final String LIST_KEY_VALUE = "list-key-value"; - private static final String DEFAULT_APP_CONFIG_FILE_PATH = "etc" + File.separator + - "opendaylight" + File.separator + "datastore" + File.separator + "initial" + - File.separator + "config"; + private static final String DEFAULT_APP_CONFIG_FILE_PATH = "etc" + File.separator + "opendaylight" + File.separator + + "datastore" + File.separator + "initial" + File.separator + "config"; private static final DocumentBuilderFactory DOC_BUILDER_FACTORY; @@ -124,21 +127,21 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor Class appConfigBindingClass; try { Class bindingClass = container.getBundleContext().getBundle().loadClass(appConfigBindingClassName); - if(!DataObject.class.isAssignableFrom(bindingClass)) { + if (!DataObject.class.isAssignableFrom(bindingClass)) { throw new ComponentDefinitionException(String.format( "%s: Specified app config binding class %s does not extend %s", logName(), appConfigBindingClassName, DataObject.class.getName())); } appConfigBindingClass = (Class) bindingClass; - } catch(ClassNotFoundException e) { + } catch (ClassNotFoundException e) { throw new ComponentDefinitionException(String.format("%s: Error loading app config binding class %s", logName(), appConfigBindingClassName), e); } - if(Identifiable.class.isAssignableFrom(appConfigBindingClass)) { + if (Identifiable.class.isAssignableFrom(appConfigBindingClass)) { // The binding class corresponds to a yang list. - if(Strings.isNullOrEmpty(appConfigListKeyValue)) { + if (Strings.isNullOrEmpty(appConfigListKeyValue)) { throw new ComponentDefinitionException(String.format( "%s: App config binding class %s represents a yang list therefore \"%s\" must be specified", logName(), appConfigBindingClassName, LIST_KEY_VALUE)); @@ -146,7 +149,8 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor try { bindingContext = ListBindingContext.newInstance(appConfigBindingClass, appConfigListKeyValue); - } catch(Exception e) { + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new ComponentDefinitionException(String.format( "%s: Error initializing for app config list binding class %s", logName(), appConfigBindingClassName), e); @@ -198,12 +202,7 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor DataTreeIdentifier dataTreeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION, bindingContext.appConfigPath); appConfigChangeListenerReg = dataBroker.registerDataTreeChangeListener(dataTreeId, - new ClusteredDataTreeChangeListener() { - @Override - public void onDataTreeChanged(Collection> changes) { - onAppConfigChanged(changes); - } - }); + (ClusteredDataTreeChangeListener) changes -> onAppConfigChanged(changes)); readInitialAppConfig(dataBroker); } @@ -216,21 +215,21 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor Futures.addCallback(future, new FutureCallback>() { @Override public void onSuccess(Optional possibleAppConfig) { - LOG.debug("{}: Read of app config {} succeeded: {}", logName(), bindingContext.appConfigBindingClass.getName(), - possibleAppConfig); + LOG.debug("{}: Read of app config {} succeeded: {}", logName(), bindingContext + .appConfigBindingClass.getName(), possibleAppConfig); readOnlyTx.close(); setInitialAppConfig(possibleAppConfig); } @Override - public void onFailure(Throwable t) { + public void onFailure(Throwable failure) { readOnlyTx.close(); // We may have gotten the app config via the data tree change listener so only retry if not. - if(readingInitialAppConfig.get()) { + if (readingInitialAppConfig.get()) { LOG.warn("{}: Read of app config {} failed - retrying", logName(), - bindingContext.appConfigBindingClass.getName(), t); + bindingContext.appConfigBindingClass.getName(), failure); readInitialAppConfig(dataBroker); } @@ -239,29 +238,29 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor } private void onAppConfigChanged(Collection> changes) { - for(DataTreeModification change: changes) { + for (DataTreeModification change: changes) { DataObjectModification changeRoot = change.getRootNode(); ModificationType type = changeRoot.getModificationType(); LOG.debug("{}: onAppConfigChanged: {}, {}", logName(), type, change.getRootPath()); - if(type == ModificationType.SUBTREE_MODIFIED || type == ModificationType.WRITE) { + if (type == ModificationType.SUBTREE_MODIFIED || type == ModificationType.WRITE) { DataObject newAppConfig = changeRoot.getDataAfter(); LOG.debug("New app config instance: {}, previous: {}", newAppConfig, currentAppConfig); - if(!setInitialAppConfig(Optional.of(newAppConfig)) && - !Objects.equals(currentAppConfig, newAppConfig)) { + if (!setInitialAppConfig(Optional.of(newAppConfig)) + && !Objects.equals(currentAppConfig, newAppConfig)) { LOG.debug("App config was updated"); - if(appConfigUpdateStrategy == UpdateStrategy.RELOAD) { + if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) { restartContainer(); } } - } else if(type == ModificationType.DELETE) { + } else if (type == ModificationType.DELETE) { LOG.debug("App config was deleted"); - if(appConfigUpdateStrategy == UpdateStrategy.RELOAD) { + if (appConfigUpdateStrategy == UpdateStrategy.RELOAD) { restartContainer(); } } @@ -270,9 +269,9 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor private boolean setInitialAppConfig(Optional possibleAppConfig) { boolean result = readingInitialAppConfig.compareAndSet(true, false); - if(result) { + if (result) { DataObject localAppConfig; - if(possibleAppConfig.isPresent()) { + if (possibleAppConfig.isPresent()) { localAppConfig = possibleAppConfig.get(); } else { // No app config data is present so create an empty instance via the bindingSerializer service. @@ -294,10 +293,11 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor private DataObject createDefaultInstance() { YangInstanceIdentifier yangPath = bindingSerializer.toYangInstanceIdentifier(bindingContext.appConfigPath); - LOG.debug("{}: Creating app config instance from path {}, Qname: {}", logName(), yangPath, bindingContext.bindingQName); + LOG.debug("{}: Creating app config instance from path {}, Qname: {}", logName(), yangPath, + bindingContext.bindingQName); SchemaService schemaService = getOSGiService(SchemaService.class); - if(schemaService == null) { + if (schemaService == null) { setFailureMessage(String.format("%s: Could not obtain the SchemaService OSGi service", logName())); return null; } @@ -306,36 +306,37 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor Module module = schemaContext.findModuleByNamespaceAndRevision(bindingContext.bindingQName.getNamespace(), bindingContext.bindingQName.getRevision()); - if(module == null) { + if (module == null) { setFailureMessage(String.format("%s: Could not obtain the module schema for namespace %s, revision %s", logName(), bindingContext.bindingQName.getNamespace(), bindingContext.bindingQName.getRevision())); return null; } DataSchemaNode dataSchema = module.getDataChildByName(bindingContext.bindingQName); - if(dataSchema == null) { - setFailureMessage(String.format("%s: Could not obtain the schema for %s", logName(), bindingContext.bindingQName)); + if (dataSchema == null) { + setFailureMessage(String.format("%s: Could not obtain the schema for %s", logName(), + bindingContext.bindingQName)); return null; } - if(!bindingContext.schemaType.isAssignableFrom(dataSchema.getClass())) { + if (!bindingContext.schemaType.isAssignableFrom(dataSchema.getClass())) { setFailureMessage(String.format("%s: Expected schema type %s for %s but actual type is %s", logName(), bindingContext.schemaType, bindingContext.bindingQName, dataSchema.getClass())); return null; } NormalizedNode dataNode = parsePossibleDefaultAppConfigXMLFile(schemaContext, dataSchema); - if(dataNode == null) { + if (dataNode == null) { dataNode = parsePossibleDefaultAppConfigElement(schemaContext, dataSchema); } - if(dataNode == null) { + if (dataNode == null) { dataNode = bindingContext.newDefaultNode(dataSchema); } DataObject appConfig = bindingSerializer.fromNormalizedNode(yangPath, dataNode).getValue(); - if(appConfig == null) { + if (appConfig == null) { // This shouldn't happen but need to handle it in case... setFailureMessage(String.format("%s: Could not create instance for app config binding %s", logName(), bindingContext.appConfigBindingClass)); @@ -348,9 +349,9 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor DataSchemaNode dataSchema) { String appConfigFileName = defaultAppConfigFileName; - if(Strings.isNullOrEmpty(appConfigFileName)) { + if (Strings.isNullOrEmpty(appConfigFileName)) { String moduleName = findYangModuleName(bindingContext.bindingQName, schemaContext); - if(moduleName == null) { + if (moduleName == null) { return null; } @@ -362,7 +363,7 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor LOG.debug("{}: parsePossibleDefaultAppConfigXMLFile looking for file {}", logName(), appConfigFile.getAbsolutePath()); - if(!appConfigFile.exists()) { + if (!appConfigFile.exists()) { return null; } @@ -371,7 +372,7 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor DomToNormalizedNodeParserFactory parserFactory = DomToNormalizedNodeParserFactory.getInstance( XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext); - try(FileInputStream fis = new FileInputStream(appConfigFile)) { + try (FileInputStream fis = new FileInputStream(appConfigFile)) { Document root = DOC_BUILDER_FACTORY.newDocumentBuilder().parse(fis); NormalizedNode dataNode = bindingContext.parseDataElement(root.getDocumentElement(), dataSchema, parserFactory); @@ -379,16 +380,18 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor LOG.debug("{}: Parsed data node: {}", logName(), dataNode); return dataNode; - } catch (Exception e) { - setFailureMessage(String.format("%s: Could not read/parse app config file %s", logName(), appConfigFile)); + } catch (SAXException | IOException | ParserConfigurationException e) { + String msg = String.format("%s: Could not read/parse app config file %s", logName(), appConfigFile); + LOG.error(msg, e); + setFailureMessage(msg); } return null; } private String findYangModuleName(QName qname, SchemaContext schemaContext) { - for(Module m: schemaContext.getModules()) { - if(qname.getModule().equals(m.getQNameModule())) { + for (Module m : schemaContext.getModules()) { + if (qname.getModule().equals(m.getQNameModule())) { return m.getName(); } } @@ -400,7 +403,7 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor @Nullable private NormalizedNode parsePossibleDefaultAppConfigElement(SchemaContext schemaContext, DataSchemaNode dataSchema) { - if(defaultAppConfigElement == null) { + if (defaultAppConfigElement == null) { return null; } @@ -425,7 +428,7 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor public void destroy(Object instance) { super.destroy(instance); - if(appConfigChangeListenerReg != null) { + if (appConfigChangeListenerReg != null) { appConfigChangeListenerReg.close(); appConfigChangeListenerReg = null; } @@ -434,7 +437,7 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor /** * Internal base class to abstract binding type-specific behavior. */ - private static abstract class BindingContext { + private abstract static class BindingContext { final InstanceIdentifier appConfigPath; final Class appConfigBindingClass; final Class schemaType; @@ -490,10 +493,11 @@ public class DataStoreAppConfigMetadata extends AbstractDependentComponentFactor @SuppressWarnings({ "rawtypes", "unchecked" }) private static ListBindingContext newInstance(Class bindingClass, String listKeyValue) - throws Exception { + throws InstantiationException, IllegalAccessException, IllegalArgumentException, + InvocationTargetException, NoSuchMethodException, SecurityException { // We assume the yang list key type is string. - Identifier keyInstance = (Identifier) bindingClass.getMethod("getKey").getReturnType(). - getConstructor(String.class).newInstance(listKeyValue); + Identifier keyInstance = (Identifier) bindingClass.getMethod("getKey").getReturnType() + .getConstructor(String.class).newInstance(listKeyValue); InstanceIdentifier appConfigPath = InstanceIdentifier.builder((Class)bindingClass, keyInstance).build(); return new ListBindingContext(bindingClass, appConfigPath, listKeyValue); } diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/NotificationListenerBean.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/NotificationListenerBean.java index c0931f32c2..ccf6216d3d 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/NotificationListenerBean.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/NotificationListenerBean.java @@ -32,6 +32,7 @@ public class NotificationListenerBean { public void setNotificationService(NotificationService notificationService) { this.notificationService = notificationService; } + public void setNotificationListener(NotificationListener notificationListener) { this.notificationListener = notificationListener; } @@ -47,7 +48,7 @@ public class NotificationListenerBean { } public void destroy() { - if(registration != null) { + if (registration != null) { LOG.debug("{}: destroy - closing ListenerRegistration {}", bundle.getSymbolicName(), notificationListener); registration.close(); } else { diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/OpendaylightNamespaceHandler.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/OpendaylightNamespaceHandler.java index 47b2c2b238..976eb7b9d5 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/OpendaylightNamespaceHandler.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/OpendaylightNamespaceHandler.java @@ -8,11 +8,13 @@ package org.opendaylight.controller.blueprint.ext; import com.google.common.base.Strings; +import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.util.Collections; import java.util.Set; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; import org.apache.aries.blueprint.ComponentDefinitionRegistry; import org.apache.aries.blueprint.NamespaceHandler; import org.apache.aries.blueprint.ParserContext; @@ -42,6 +44,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; +import org.xml.sax.SAXException; /** * The NamespaceHandler for Opendaylight blueprint extensions. @@ -76,7 +79,7 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { @Override public URL getSchemaLocation(String namespace) { - if(NAMESPACE_1_0_0.equals(namespace)) { + if (NAMESPACE_1_0_0.equals(namespace)) { URL url = getClass().getResource("/opendaylight-blueprint-ext-1.0.0.xsd"); LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url); return url; @@ -110,20 +113,20 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { @Override public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) { - if(node instanceof Attr) { + if (node instanceof Attr) { if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) { - return decorateRestartDependentsOnUpdates((Attr)node, component, context); + return decorateRestartDependentsOnUpdates((Attr) node, component, context); } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) { - return decorateUseDefaultForReferenceTypes((Attr)node, component, context); + return decorateUseDefaultForReferenceTypes((Attr) node, component, context); } else if (nodeNameEquals(node, TYPE_ATTR)) { - if(component instanceof ServiceReferenceMetadata) { - return decorateServiceReferenceType((Attr)node, component, context); - } else if(component instanceof ServiceMetadata) { + if (component instanceof ServiceReferenceMetadata) { + return decorateServiceReferenceType((Attr) node, component, context); + } else if (component instanceof ServiceMetadata) { return decorateServiceType((Attr)node, component, context); } - throw new ComponentDefinitionException("Attribute " + node.getNodeName() + - " can only be used on a , or element"); + throw new ComponentDefinitionException("Attribute " + node.getNodeName() + + " can only be used on a , or element"); } throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName()); @@ -145,7 +148,8 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { return component; } - private ComponentMetadata decorateServiceReferenceType(Attr attr, ComponentMetadata component, ParserContext context) { + private ComponentMetadata decorateServiceReferenceType(Attr attr, ComponentMetadata component, + ParserContext context) { if (!(component instanceof MutableServiceReferenceMetadata)) { throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata"); } @@ -163,7 +167,7 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { serviceRef.getExtendedFilter().getStringValue(); String filter; - if(Strings.isNullOrEmpty(oldFilter)) { + if (Strings.isNullOrEmpty(oldFilter)) { filter = String.format("(type=%s)", attr.getValue()); } else { filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue()); @@ -188,14 +192,14 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { private static ComponentMetadata enableComponentProcessorProperty(Attr attr, ComponentMetadata component, ParserContext context, String propertyName) { - if(component != null) { - throw new ComponentDefinitionException("Attribute " + attr.getNodeName() + - " can only be used on the root element"); + if (component != null) { + throw new ComponentDefinitionException("Attribute " + attr.getNodeName() + + " can only be used on the root element"); } LOG.debug("{}: {}", propertyName, attr.getValue()); - if(!Boolean.parseBoolean(attr.getValue())) { + if (!Boolean.parseBoolean(attr.getValue())) { return component; } @@ -208,7 +212,7 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { private static MutableBeanMetadata registerComponentProcessor(ParserContext context) { ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry(); MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME); - if(metadata == null) { + if (metadata == null) { metadata = context.createMetadata(MutableBeanMetadata.class); metadata.setProcessor(true); metadata.setId(COMPONENT_PROCESSOR_NAME); @@ -242,7 +246,7 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { metadata.addProperty("rpcRegistry", createRef(context, RPC_REGISTRY_NAME)); metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR))); - if(element.hasAttribute(INTERFACE)) { + if (element.hasAttribute(INTERFACE)) { metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE))); } @@ -274,7 +278,7 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { private void registerRoutedRpcRegistrationConverter(ParserContext context) { ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry(); - if(registry.getComponentDefinition(ROUTED_RPC_REG_CONVERTER_NAME) == null) { + if (registry.getComponentDefinition(ROUTED_RPC_REG_CONVERTER_NAME) == null) { MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class); metadata.setId(ROUTED_RPC_REG_CONVERTER_NAME); metadata.setScope(BeanMetadata.SCOPE_SINGLETON); @@ -286,7 +290,7 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { private void registerRpcRegistryServiceRefBean(ParserContext context) { ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry(); - if(registry.getComponentDefinition(RPC_REGISTRY_NAME) == null) { + if (registry.getComponentDefinition(RPC_REGISTRY_NAME) == null) { MutableReferenceMetadata metadata = createServiceRef(context, RpcProviderRegistry.class, null); metadata.setId(RPC_REGISTRY_NAME); registry.registerComponentDefinition(metadata); @@ -314,7 +318,7 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { private void registerNotificationServiceRefBean(ParserContext context) { ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry(); - if(registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) { + if (registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) { MutableReferenceMetadata metadata = createServiceRef(context, NotificationService.class, null); metadata.setId(NOTIFICATION_SERVICE_NAME); registry.registerComponentDefinition(metadata); @@ -327,22 +331,23 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { // Find the default-config child element representing the default app config XML, if present. Element defaultConfigElement = null; NodeList children = element.getChildNodes(); - for(int i = 0; i < children.getLength(); i++) { + for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); - if(nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) { + if (nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) { defaultConfigElement = (Element) child; break; } } Element defaultAppConfigElement = null; - if(defaultConfigElement != null) { + if (defaultConfigElement != null) { // Find the CDATA element containing the default app config XML. children = defaultConfigElement.getChildNodes(); - for(int i = 0; i < children.getLength(); i++) { + for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); - if(child.getNodeType() == Node.CDATA_SECTION_NODE) { - defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG, child.getTextContent()); + if (child.getNodeType() == Node.CDATA_SECTION_NODE) { + defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG, + child.getTextContent()); break; } } @@ -356,10 +361,10 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { } private UpdateStrategy parseUpdateStrategy(String updateStrategyValue) { - if (Strings.isNullOrEmpty(updateStrategyValue) || - updateStrategyValue.equalsIgnoreCase(UpdateStrategy.RELOAD.name())) { + if (Strings.isNullOrEmpty(updateStrategyValue) + || updateStrategyValue.equalsIgnoreCase(UpdateStrategy.RELOAD.name())) { return UpdateStrategy.RELOAD; - } else if(updateStrategyValue.equalsIgnoreCase(UpdateStrategy.NONE.name())){ + } else if (updateStrategyValue.equalsIgnoreCase(UpdateStrategy.NONE.name())) { return UpdateStrategy.NONE; } else { LOG.warn("update-strategy {} not supported, using reload", updateStrategyValue); @@ -393,30 +398,31 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { builderFactory.setIgnoringComments(true); try { - return builderFactory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement(); - } catch(Exception e) { - throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml)); + return builderFactory.newDocumentBuilder().parse(new InputSource( + new StringReader(xml))).getDocumentElement(); + } catch (SAXException | IOException | ParserConfigurationException e) { + throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml), e); } } private static ValueMetadata createValue(ParserContext context, String value) { - MutableValueMetadata m = context.createMetadata(MutableValueMetadata.class); - m.setStringValue(value); - return m; + MutableValueMetadata metadata = context.createMetadata(MutableValueMetadata.class); + metadata.setStringValue(value); + return metadata; } private static MutableReferenceMetadata createServiceRef(ParserContext context, Class cls, String filter) { - MutableReferenceMetadata m = context.createMetadata(MutableReferenceMetadata.class); - m.setRuntimeInterface(cls); - m.setInterface(cls.getName()); - m.setActivation(ReferenceMetadata.ACTIVATION_EAGER); - m.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY); - - if(filter != null) { - m.setFilter(filter); + MutableReferenceMetadata metadata = context.createMetadata(MutableReferenceMetadata.class); + metadata.setRuntimeInterface(cls); + metadata.setInterface(cls.getName()); + metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER); + metadata.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY); + + if (filter != null) { + metadata.setFilter(filter); } - return m; + return metadata; } private static RefMetadata createRef(ParserContext context, String id) { @@ -426,7 +432,7 @@ public class OpendaylightNamespaceHandler implements NamespaceHandler { } private static String getId(ParserContext context, Element element) { - if(element.hasAttribute(ID_ATTR)) { + if (element.hasAttribute(ID_ATTR)) { return element.getAttribute(ID_ATTR); } else { return context.generateId(); diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RoutedRpcMetadata.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RoutedRpcMetadata.java index 7bf559ea4c..04e6d30620 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RoutedRpcMetadata.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RoutedRpcMetadata.java @@ -56,12 +56,13 @@ class RoutedRpcMetadata implements ComponentFactoryMetadata { } @Override - public void init(ExtendedBlueprintContainer container) { - this.container = container; + public void init(ExtendedBlueprintContainer newContainer) { + this.container = newContainer; LOG.debug("{}: In init", logName()); } + @SuppressWarnings("checkstyle:IllegalCatch") @Override public Object create() throws ComponentDefinitionException { RpcProviderRegistry rpcRegistry = (RpcProviderRegistry) container.getComponentInstance( @@ -70,7 +71,7 @@ class RoutedRpcMetadata implements ComponentFactoryMetadata { Object implementation = container.getComponentInstance(implementationRefId); try { - if(!RpcService.class.isAssignableFrom(implementation.getClass())) { + if (!RpcService.class.isAssignableFrom(implementation.getClass())) { throw new ComponentDefinitionException(String.format( "Implementation \"ref\" instance %s for \"%s\" is not an RpcService", implementation.getClass(), ROUTED_RPC_IMPLEMENTATION)); @@ -80,10 +81,10 @@ class RoutedRpcMetadata implements ComponentFactoryMetadata { interfaceName, implementation.getClass(), container.getBundleContext().getBundle(), ROUTED_RPC_IMPLEMENTATION); - if(rpcInterfaces.size() > 1) { + if (rpcInterfaces.size() > 1) { throw new ComponentDefinitionException(String.format( - "Implementation \"ref\" instance %s for \"%s\" implements more than one RpcService " + - "interface (%s). Please specify the exact \"interface\"", implementation.getClass(), + "Implementation \"ref\" instance %s for \"%s\" implements more than one RpcService " + + "interface (%s). Please specify the exact \"interface\"", implementation.getClass(), ROUTED_RPC_IMPLEMENTATION, rpcInterfaces)); } @@ -93,9 +94,9 @@ class RoutedRpcMetadata implements ComponentFactoryMetadata { implementation, rpcInterface); return rpcRegistry.addRoutedRpcImplementation(rpcInterface, (RpcService)implementation); - } catch(ComponentDefinitionException e) { + } catch (ComponentDefinitionException e) { throw e; - } catch(Exception e) { + } catch (Exception e) { throw new ComponentDefinitionException(String.format( "Error processing \"%s\" for %s", ROUTED_RPC_IMPLEMENTATION, implementation.getClass()), e); } @@ -109,7 +110,6 @@ class RoutedRpcMetadata implements ComponentFactoryMetadata { } private String logName() { - return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + - " (" + id + ")"; + return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + " (" + id + ")"; } } diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RoutedRpcRegistrationConverter.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RoutedRpcRegistrationConverter.java index 7daf7febf6..5ae9a1cf72 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RoutedRpcRegistrationConverter.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RoutedRpcRegistrationConverter.java @@ -23,8 +23,8 @@ import org.osgi.service.blueprint.container.ReifiedType; public class RoutedRpcRegistrationConverter implements Converter { @Override public boolean canConvert(Object sourceObject, ReifiedType targetType) { - return sourceObject instanceof RoutedRpcRegistration && - RoutedRpcRegistration.class.isAssignableFrom(targetType.getRawClass()); + return sourceObject instanceof RoutedRpcRegistration + && RoutedRpcRegistration.class.isAssignableFrom(targetType.getRawClass()); } @Override diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RpcImplementationBean.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RpcImplementationBean.java index 1ab78db9cd..3144328c99 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RpcImplementationBean.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RpcImplementationBean.java @@ -51,6 +51,7 @@ public class RpcImplementationBean { this.implementation = implementation; } + @SuppressWarnings("checkstyle:IllegalCatch") public void init() { try { List> rpcInterfaces = getImplementedRpcServiceInterfaces(interfaceName, @@ -59,19 +60,19 @@ public class RpcImplementationBean { LOG.debug("{}: init - adding implementation {} for RpcService interface(s) {}", bundle.getSymbolicName(), implementation, rpcInterfaces); - for(Class rpcInterface: rpcInterfaces) { + for (Class rpcInterface : rpcInterfaces) { rpcRegistrations.add(rpcRegistry.addRpcImplementation(rpcInterface, implementation)); } - } catch(ComponentDefinitionException e) { + } catch (ComponentDefinitionException e) { throw e; - } catch(Exception e) { + } catch (Exception e) { throw new ComponentDefinitionException(String.format( "Error processing \"%s\" for %s", RPC_IMPLEMENTATION, implementation.getClass()), e); } } public void destroy() { - for(RpcRegistration reg: rpcRegistrations) { + for (RpcRegistration reg: rpcRegistrations) { reg.close(); } } @@ -79,10 +80,10 @@ public class RpcImplementationBean { @SuppressWarnings("unchecked") static List> getImplementedRpcServiceInterfaces(String interfaceName, Class implementationClass, Bundle bundle, String logName) throws ClassNotFoundException { - if(!Strings.isNullOrEmpty(interfaceName)) { + if (!Strings.isNullOrEmpty(interfaceName)) { Class rpcInterface = bundle.loadClass(interfaceName); - if(!rpcInterface.isAssignableFrom(implementationClass)) { + if (!rpcInterface.isAssignableFrom(implementationClass)) { throw new ComponentDefinitionException(String.format( "The specified \"interface\" %s for \"%s\" is not implemented by RpcService \"ref\" %s", interfaceName, logName, implementationClass)); @@ -92,13 +93,13 @@ public class RpcImplementationBean { } List> rpcInterfaces = new ArrayList<>(); - for(Class intface: implementationClass.getInterfaces()) { - if(RpcService.class.isAssignableFrom(intface)) { + for (Class intface : implementationClass.getInterfaces()) { + if (RpcService.class.isAssignableFrom(intface)) { rpcInterfaces.add((Class) intface); } } - if(rpcInterfaces.isEmpty()) { + if (rpcInterfaces.isEmpty()) { throw new ComponentDefinitionException(String.format( "The \"ref\" instance %s for \"%s\" does not implemented any RpcService interfaces", implementationClass, logName)); diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RpcServiceMetadata.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RpcServiceMetadata.java index 82b1b6be15..652180725c 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RpcServiceMetadata.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/RpcServiceMetadata.java @@ -48,20 +48,22 @@ class RpcServiceMetadata extends AbstractDependentComponentFactoryMetadata { this.interfaceName = interfaceName; } + @SuppressWarnings({ "checkstyle:IllegalCatch", "unchecked" }) @Override - @SuppressWarnings("unchecked") public void init(ExtendedBlueprintContainer container) { super.init(container); try { Class interfaceClass = container().getBundleContext().getBundle().loadClass(interfaceName); - if(!RpcService.class.isAssignableFrom(interfaceClass)) { + if (!RpcService.class.isAssignableFrom(interfaceClass)) { throw new ComponentDefinitionException(String.format( "%s: The specified interface %s is not an RpcService", logName(), interfaceName)); } rpcInterface = (Class)interfaceClass; - } catch(Exception e) { + } catch (ComponentDefinitionException e) { + throw e; + } catch (Exception e) { throw new ComponentDefinitionException(String.format("%s: Error obtaining interface class %s", logName(), interfaceName), e); } @@ -72,19 +74,20 @@ class RpcServiceMetadata extends AbstractDependentComponentFactoryMetadata { // First get the SchemaContext. This will be used to get the RPC SchemaPaths. retrieveService("SchemaService", SchemaService.class, - service -> retrievedSchemaContext(((SchemaService)service).getGlobalContext())); + service -> retrievedSchemaContext(((SchemaService)service).getGlobalContext())); } private void retrievedSchemaContext(SchemaContext schemaContext) { LOG.debug("{}: retrievedSchemaContext", logName()); QNameModule moduleName = BindingReflections.getQNameModule(rpcInterface); - Module module = schemaContext.findModuleByNamespaceAndRevision(moduleName.getNamespace(), moduleName.getRevision()); + Module module = schemaContext.findModuleByNamespaceAndRevision(moduleName.getNamespace(), + moduleName.getRevision()); LOG.debug("{}: Got Module: {}", logName(), module); rpcSchemaPaths = new HashSet<>(); - for(RpcDefinition rpcDef : module.getRpcs()) { + for (RpcDefinition rpcDef : module.getRpcs()) { rpcSchemaPaths.add(rpcDef.getPath()); } @@ -93,7 +96,8 @@ class RpcServiceMetadata extends AbstractDependentComponentFactoryMetadata { // First get the DOMRpcService OSGi service. This will be used to register a listener to be notified // when the underlying DOM RPC service is available. - retrieveService("DOMRpcService", DOMRpcService.class, service -> retrievedDOMRpcService((DOMRpcService)service)); + retrieveService("DOMRpcService", DOMRpcService.class, + service -> retrievedDOMRpcService((DOMRpcService)service)); } private void retrievedDOMRpcService(DOMRpcService domRpcService) { @@ -112,8 +116,8 @@ class RpcServiceMetadata extends AbstractDependentComponentFactoryMetadata { } protected void onRpcsAvailable(Collection rpcs) { - for(DOMRpcIdentifier identifier: rpcs) { - if(rpcSchemaPaths.contains(identifier.getType())) { + for (DOMRpcIdentifier identifier : rpcs) { + if (rpcSchemaPaths.contains(identifier.getType())) { LOG.debug("{}: onRpcsAvailable - found SchemaPath {}", logName(), identifier.getType()); retrieveService("RpcProviderRegistry", RpcProviderRegistry.class, service -> { @@ -126,6 +130,7 @@ class RpcServiceMetadata extends AbstractDependentComponentFactoryMetadata { } } + @SuppressWarnings("checkstyle:IllegalCatch") @Override public Object create() throws ComponentDefinitionException { LOG.debug("{}: In create: interfaceName: {}", logName(), interfaceName); @@ -138,7 +143,7 @@ class RpcServiceMetadata extends AbstractDependentComponentFactoryMetadata { LOG.debug("{}: create returning service {}", logName(), rpcService); return rpcService; - } catch(Exception e) { + } catch (RuntimeException e) { throw new ComponentDefinitionException("Error getting RPC service for " + interfaceName, e); } } @@ -150,7 +155,7 @@ class RpcServiceMetadata extends AbstractDependentComponentFactoryMetadata { } private void closeRpcListenerReg() { - if(rpcListenerReg != null) { + if (rpcListenerReg != null) { rpcListenerReg.close(); rpcListenerReg = null; } diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/SpecificReferenceListMetadata.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/SpecificReferenceListMetadata.java index 553b364d77..02086410f6 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/SpecificReferenceListMetadata.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/SpecificReferenceListMetadata.java @@ -76,13 +76,13 @@ class SpecificReferenceListMetadata extends AbstractDependentComponentFactoryMet } }; - bundleTracker = new BundleTracker<>(container().getBundleContext(), Bundle.RESOLVED | Bundle.STARTING | - Bundle.STOPPING | Bundle.ACTIVE, bundleListener); + bundleTracker = new BundleTracker<>(container().getBundleContext(), Bundle.RESOLVED | Bundle.STARTING + | Bundle.STOPPING | Bundle.ACTIVE, bundleListener); // This will get the list of all current RESOLVED+ bundles. bundleTracker.open(); - if(expectedServiceTypes.isEmpty()) { + if (expectedServiceTypes.isEmpty()) { setSatisfied(); return; } @@ -111,21 +111,21 @@ class SpecificReferenceListMetadata extends AbstractDependentComponentFactoryMet private void bundleAdded(Bundle bundle) { URL resource = bundle.getEntry(serviceResourcePath); - if(resource == null) { + if (resource == null) { return; } LOG.debug("{}: Found {} resource in bundle {}", logName(), resource, bundle.getSymbolicName()); try { - for(String line : Resources.readLines(resource, StandardCharsets.UTF_8)) { + for (String line : Resources.readLines(resource, StandardCharsets.UTF_8)) { int ci = line.indexOf('#'); - if(ci >= 0) { + if (ci >= 0) { line = line.substring(0, ci); } line = line.trim(); - if(line.isEmpty()) { + if (line.isEmpty()) { continue; } @@ -133,7 +133,7 @@ class SpecificReferenceListMetadata extends AbstractDependentComponentFactoryMet LOG.debug("{}: Retrieved service type {}", logName(), serviceType); expectedServiceTypes.add(serviceType); } - } catch(IOException e) { + } catch (IOException e) { setFailure(String.format("%s: Error reading resource %s from bundle %s", logName(), resource, bundle.getSymbolicName()), e); } @@ -146,30 +146,30 @@ class SpecificReferenceListMetadata extends AbstractDependentComponentFactoryMet LOG.debug("{}: Service type {} added from bundle {}", logName(), serviceType, reference.getBundle().getSymbolicName()); - if(serviceType == null) { + if (serviceType == null) { LOG.error("{}: Missing OSGi service property '{}' for service interface {} in bundle {}", logName(), OpendaylightNamespaceHandler.TYPE_ATTR, interfaceName, reference.getBundle().getSymbolicName()); return service; } - if(!expectedServiceTypes.contains(serviceType)) { - LOG.error("{}: OSGi service property '{}' for service interface {} in bundle {} was not found in the " + - "expected service types {} obtained via {} bundle resources. Is the bundle resource missing or the service type misspelled?", - logName(), OpendaylightNamespaceHandler.TYPE_ATTR, interfaceName, reference.getBundle().getSymbolicName(), - expectedServiceTypes, serviceResourcePath); + if (!expectedServiceTypes.contains(serviceType)) { + LOG.error("{}: OSGi service property '{}' for service interface {} in bundle {} was not found in the " + + "expected service types {} obtained via {} bundle resources. Is the bundle resource missing or " + + "the service type misspelled?", logName(), OpendaylightNamespaceHandler.TYPE_ATTR, interfaceName, + reference.getBundle().getSymbolicName(), expectedServiceTypes, serviceResourcePath); return service; } // If already satisfied, meaning we got all initial services, then a new bundle must've been // dynamically installed or a prior service's blueprint container was restarted, in which case we // restart our container. - if(isSatisfied()) { + if (isSatisfied()) { restartContainer(); } else { retrievedServiceTypes.add(serviceType.toString()); retrievedServices.add(service); - if(retrievedServiceTypes.equals(expectedServiceTypes)) { + if (retrievedServiceTypes.equals(expectedServiceTypes)) { LOG.debug("{}: Got all expected service types", logName()); setSatisfied(); } else { @@ -190,7 +190,7 @@ class SpecificReferenceListMetadata extends AbstractDependentComponentFactoryMet LOG.debug("{}: create returning service list {}", logName(), retrievedServices); - synchronized(retrievedServices) { + synchronized (retrievedServices) { return ImmutableList.copyOf(retrievedServices); } } @@ -199,12 +199,12 @@ class SpecificReferenceListMetadata extends AbstractDependentComponentFactoryMet public void destroy(Object instance) { super.destroy(instance); - if(bundleTracker != null) { + if (bundleTracker != null) { bundleTracker.close(); bundleTracker = null; } - if(serviceTracker != null) { + if (serviceTracker != null) { serviceTracker.close(); serviceTracker = null; } diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/StaticServiceReferenceRecipe.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/StaticServiceReferenceRecipe.java index 0466aab6c2..3689805655 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/StaticServiceReferenceRecipe.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/StaticServiceReferenceRecipe.java @@ -11,7 +11,6 @@ import com.google.common.base.Preconditions; import java.util.Collections; import java.util.function.Consumer; import org.apache.aries.blueprint.container.AbstractServiceReferenceRecipe; -import org.apache.aries.blueprint.container.SatisfiableRecipe; import org.apache.aries.blueprint.services.ExtendedBlueprintContainer; import org.osgi.framework.ServiceReference; import org.osgi.service.blueprint.container.ComponentDefinitionException; @@ -28,11 +27,8 @@ import org.slf4j.LoggerFactory; class StaticServiceReferenceRecipe extends AbstractServiceReferenceRecipe { private static final Logger LOG = LoggerFactory.getLogger(StaticServiceReferenceRecipe.class); - private static final SatisfactionListener NOOP_LISTENER = new SatisfactionListener() { - @Override - public void notifySatisfaction(SatisfiableRecipe satisfiable) { + private static final SatisfactionListener NOOP_LISTENER = satisfiable -> { - } }; private volatile ServiceReference trackedServiceReference; @@ -45,8 +41,8 @@ class StaticServiceReferenceRecipe extends AbstractServiceReferenceRecipe { Collections.emptyList()); } - void startTracking(Consumer serviceSatisfiedCallback) { - this.serviceSatisfiedCallback = serviceSatisfiedCallback; + void startTracking(Consumer newServiceSatisfiedCallback) { + this.serviceSatisfiedCallback = newServiceSatisfiedCallback; super.start(NOOP_LISTENER); } @@ -61,7 +57,7 @@ class StaticServiceReferenceRecipe extends AbstractServiceReferenceRecipe { protected void untrack(ServiceReference reference) { LOG.debug("{}: In untrack {}", getName(), reference); - if(trackedServiceReference == reference) { + if (trackedServiceReference == reference) { LOG.debug("{}: Current reference has been untracked", getName(), trackedServiceReference); } } @@ -70,12 +66,12 @@ class StaticServiceReferenceRecipe extends AbstractServiceReferenceRecipe { protected void retrack() { LOG.debug("{}: In retrack", getName()); - if(trackedServiceReference == null) { + if (trackedServiceReference == null) { trackedServiceReference = getBestServiceReference(); LOG.debug("{}: getBestServiceReference: {}", getName(), trackedServiceReference); - if(trackedServiceReference != null && serviceSatisfiedCallback != null) { + if (trackedServiceReference != null && serviceSatisfiedCallback != null) { serviceSatisfiedCallback.accept(internalCreate()); } } @@ -85,10 +81,10 @@ class StaticServiceReferenceRecipe extends AbstractServiceReferenceRecipe { protected void doStop() { LOG.debug("{}: In doStop", getName()); - if(trackedServiceReference != null && trackedService != null) { + if (trackedServiceReference != null && trackedService != null) { try { getBundleContextForServiceLookup().ungetService(trackedServiceReference); - } catch(IllegalStateException e) { + } catch (IllegalStateException e) { // In case the service no longer exists, ignore. } @@ -104,7 +100,7 @@ class StaticServiceReferenceRecipe extends AbstractServiceReferenceRecipe { LOG.debug("{}: In internalCreate: trackedServiceReference: {}", getName(), localTrackedServiceReference); // being paranoid - internalCreate should only get called once - if(trackedService != null) { + if (trackedService != null) { return trackedService; } diff --git a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/UpdateStrategy.java b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/UpdateStrategy.java index 1b5d128005..2f83bc688f 100644 --- a/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/UpdateStrategy.java +++ b/opendaylight/blueprint/src/main/java/org/opendaylight/controller/blueprint/ext/UpdateStrategy.java @@ -8,7 +8,7 @@ package org.opendaylight.controller.blueprint.ext; /** - * Enumerates possible strategies when a component is updated + * Enumerates possible strategies when a component is updated. * * @author Vishal Thapar */ -- 2.36.6