</instructions>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+ </configuration>
+ </plugin>
</plugins>
</build>
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;
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();
}
}
*/
@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<Object> paths = findBlueprintPaths(bundle);
- if(!paths.isEmpty()) {
+ if (!paths.isEmpty()) {
LOG.info("Creating blueprint container for bundle {} with paths {}", bundle, paths);
blueprintExtenderService.createContainer(bundle, paths);
/**
* 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<Object> 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));
@SuppressWarnings({ "rawtypes", "unchecked" })
static List<Object> 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);
}
}
// 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<Bundle> 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);
}
}
// 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<Bundle>() {
- @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 {
// 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());
}
private <T> T getOSGiService(Class<T> serviceInterface) {
try {
ServiceReference<T> 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);
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;
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) {
}
public void restartContainer(final Bundle bundle, final List<Object> 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) {
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));
}
// 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<Object> paths = BlueprintBundleTracker.findBlueprintPaths(bundle);
LOG.info("Restarting blueprint container for bundle {} with paths {}", bundle, paths);
try {
containerCreationComplete.await(5, TimeUnit.MINUTES);
- } catch(InterruptedException e) {
+ } catch (InterruptedException e) {
LOG.debug("CountDownLatch await was interrupted - returning");
return;
}
restartConfigModules(forBundle.getBundleContext(), configModules);
}
- private void restartConfigModules(BundleContext bundleContext, List<Entry<String, ModuleIdentifier>> configModules) {
- if(configModules.isEmpty()) {
+ private void restartConfigModules(BundleContext bundleContext, List<Entry<String,
+ ModuleIdentifier>> configModules) {
+ if (configModules.isEmpty()) {
return;
}
- ServiceReference<ConfigSubsystemFacadeFactory> configFacadeFactoryRef =
- bundleContext.getServiceReference(ConfigSubsystemFacadeFactory.class);
- if(configFacadeFactoryRef == null) {
+ ServiceReference<ConfigSubsystemFacadeFactory> 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;
}
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();
Config configMapping = configFacade.getConfigMapping();
ConfigRegistry configRegistryClient = new ConfigRegistryJMXClient(ManagementFactory.getPlatformMBeanServer());
- for(Entry<String, ModuleIdentifier> entry: configModules) {
+ for (Entry<String, ModuleIdentifier> entry: configModules) {
String moduleNamespace = entry.getKey();
ModuleIdentifier moduleId = entry.getValue();
try {
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));
}
*/
private void findDependentContainersRecursively(Bundle bundle, Set<Bundle> containerBundles,
List<Entry<String, ModuleIdentifier>> configModules) {
- if(!containerBundles.add(bundle)) {
+ if (!containerBundles.add(bundle)) {
// Already seen this bundle...
return;
}
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);
}
}
private void possiblyAddConfigModuleIdentifier(ServiceReference<?> reference,
List<Entry<String, ModuleIdentifier>> configModules) {
Object moduleNamespace = reference.getProperty(CONFIG_MODULE_NAMESPACE_PROP);
- if(moduleNamespace == null) {
+ if (moduleNamespace == null) {
return;
}
reference);
String instanceName = getRequiredConfigModuleProperty(CONFIG_INSTANCE_NAME_PROP, moduleNamespace,
reference);
- if(moduleName == null || instanceName == null) {
+ if (moduleName == null || instanceName == null) {
return;
}
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;
}
import org.slf4j.LoggerFactory;
/**
+ * Abstract base class for a DependentComponentFactoryMetadata implementation.
+ *
* @author Thomas Pantelis
*/
abstract class AbstractDependentComponentFactoryMetadata implements DependentComponentFactoryMetadata {
return satisfied.get();
}
- protected abstract void startTracking();
-
protected void setFailureMessage(String failureMessage) {
setFailure(failureMessage, null);
}
}
protected void setSatisfied() {
- if(satisfied.compareAndSet(false, true)) {
+ if (satisfied.compareAndSet(false, true)) {
satisfactionCallback.notifyChanged();
}
}
}
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);
}
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 {
}
}
+ 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();
}
}
private void stopServiceRecipes() {
- for(StaticServiceReferenceRecipe recipe: serviceRecipes) {
+ for (StaticServiceReferenceRecipe recipe: serviceRecipes) {
recipe.stop();
}
}
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());
}
try {
ServiceReference<T> 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);
}
public void destroy() {
- for(ServiceRegistration<?> reg: managedServiceRegs) {
+ for (ServiceRegistration<?> reg: managedServiceRegs) {
AriesFrameworkUtil.safeUnregisterService(reg);
}
}
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;
}
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(),
}
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(),
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
// 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);
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;
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;
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;
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
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;
Class<DataObject> 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<DataObject>) 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));
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);
DataTreeIdentifier<DataObject> dataTreeId = new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
bindingContext.appConfigPath);
appConfigChangeListenerReg = dataBroker.registerDataTreeChangeListener(dataTreeId,
- new ClusteredDataTreeChangeListener<DataObject>() {
- @Override
- public void onDataTreeChanged(Collection<DataTreeModification<DataObject>> changes) {
- onAppConfigChanged(changes);
- }
- });
+ (ClusteredDataTreeChangeListener<DataObject>) changes -> onAppConfigChanged(changes));
readInitialAppConfig(dataBroker);
}
Futures.addCallback(future, new FutureCallback<Optional<DataObject>>() {
@Override
public void onSuccess(Optional<DataObject> 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);
}
}
private void onAppConfigChanged(Collection<DataTreeModification<DataObject>> changes) {
- for(DataTreeModification<DataObject> change: changes) {
+ for (DataTreeModification<DataObject> change: changes) {
DataObjectModification<DataObject> 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();
}
}
private boolean setInitialAppConfig(Optional<DataObject> 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.
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;
}
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));
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;
}
LOG.debug("{}: parsePossibleDefaultAppConfigXMLFile looking for file {}", logName(),
appConfigFile.getAbsolutePath());
- if(!appConfigFile.exists()) {
+ if (!appConfigFile.exists()) {
return null;
}
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);
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();
}
}
@Nullable
private NormalizedNode<?, ?> parsePossibleDefaultAppConfigElement(SchemaContext schemaContext,
DataSchemaNode dataSchema) {
- if(defaultAppConfigElement == null) {
+ if (defaultAppConfigElement == null) {
return null;
}
public void destroy(Object instance) {
super.destroy(instance);
- if(appConfigChangeListenerReg != null) {
+ if (appConfigChangeListenerReg != null) {
appConfigChangeListenerReg.close();
appConfigChangeListenerReg = null;
}
/**
* Internal base class to abstract binding type-specific behavior.
*/
- private static abstract class BindingContext {
+ private abstract static class BindingContext {
final InstanceIdentifier<DataObject> appConfigPath;
final Class<DataObject> appConfigBindingClass;
final Class<? extends DataSchemaNode> schemaType;
@SuppressWarnings({ "rawtypes", "unchecked" })
private static ListBindingContext newInstance(Class<DataObject> 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);
}
public void setNotificationService(NotificationService notificationService) {
this.notificationService = notificationService;
}
+
public void setNotificationListener(NotificationListener notificationListener) {
this.notificationListener = notificationListener;
}
}
public void destroy() {
- if(registration != null) {
+ if (registration != null) {
LOG.debug("{}: destroy - closing ListenerRegistration {}", bundle.getSymbolicName(), notificationListener);
registration.close();
} else {
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;
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.
@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;
@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 <reference>, <reference-list> or <service> element");
+ throw new ComponentDefinitionException("Attribute " + node.getNodeName()
+ + " can only be used on a <reference>, <reference-list> or <service> element");
}
throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
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");
}
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());
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 <blueprint> element");
+ if (component != null) {
+ throw new ComponentDefinitionException("Attribute " + attr.getNodeName()
+ + " can only be used on the root <blueprint> element");
}
LOG.debug("{}: {}", propertyName, attr.getValue());
- if(!Boolean.parseBoolean(attr.getValue())) {
+ if (!Boolean.parseBoolean(attr.getValue())) {
return component;
}
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);
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)));
}
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);
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);
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);
// 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;
}
}
}
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);
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) {
}
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();
}
@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(
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));
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));
}
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);
}
}
private String logName() {
- return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") +
- " (" + id + ")";
+ return (container != null ? container.getBundleContext().getBundle().getSymbolicName() : "") + " (" + id + ")";
}
}
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
this.implementation = implementation;
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
public void init() {
try {
List<Class<RpcService>> rpcInterfaces = getImplementedRpcServiceInterfaces(interfaceName,
LOG.debug("{}: init - adding implementation {} for RpcService interface(s) {}", bundle.getSymbolicName(),
implementation, rpcInterfaces);
- for(Class<RpcService> rpcInterface: rpcInterfaces) {
+ for (Class<RpcService> 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<RpcService> reg: rpcRegistrations) {
+ for (RpcRegistration<RpcService> reg: rpcRegistrations) {
reg.close();
}
}
@SuppressWarnings("unchecked")
static List<Class<RpcService>> 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));
}
List<Class<RpcService>> 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<RpcService>) 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));
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<RpcService>)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);
}
// 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());
}
// 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) {
}
protected void onRpcsAvailable(Collection<DOMRpcIdentifier> 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 -> {
}
}
+ @SuppressWarnings("checkstyle:IllegalCatch")
@Override
public Object create() throws ComponentDefinitionException {
LOG.debug("{}: In create: interfaceName: {}", logName(), interfaceName);
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);
}
}
}
private void closeRpcListenerReg() {
- if(rpcListenerReg != null) {
+ if (rpcListenerReg != null) {
rpcListenerReg.close();
rpcListenerReg = null;
}
}
};
- 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;
}
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;
}
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);
}
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 {
LOG.debug("{}: create returning service list {}", logName(), retrievedServices);
- synchronized(retrievedServices) {
+ synchronized (retrievedServices) {
return ImmutableList.copyOf(retrievedServices);
}
}
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;
}
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;
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;
Collections.emptyList());
}
- void startTracking(Consumer<Object> serviceSatisfiedCallback) {
- this.serviceSatisfiedCallback = serviceSatisfiedCallback;
+ void startTracking(Consumer<Object> newServiceSatisfiedCallback) {
+ this.serviceSatisfiedCallback = newServiceSatisfiedCallback;
super.start(NOOP_LISTENER);
}
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);
}
}
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());
}
}
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.
}
LOG.debug("{}: In internalCreate: trackedServiceReference: {}", getName(), localTrackedServiceReference);
// being paranoid - internalCreate should only get called once
- if(trackedService != null) {
+ if (trackedService != null) {
return trackedService;
}
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
*/