2 * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.blueprint.ext;
10 import com.google.common.base.Strings;
11 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
12 import java.io.IOException;
13 import java.io.StringReader;
15 import java.util.Collections;
17 import org.apache.aries.blueprint.ComponentDefinitionRegistry;
18 import org.apache.aries.blueprint.NamespaceHandler;
19 import org.apache.aries.blueprint.ParserContext;
20 import org.apache.aries.blueprint.ext.ComponentFactoryMetadata;
21 import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
22 import org.apache.aries.blueprint.mutable.MutableRefMetadata;
23 import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
24 import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
25 import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
26 import org.apache.aries.blueprint.mutable.MutableValueMetadata;
27 import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
28 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
29 import org.opendaylight.mdsal.binding.api.NotificationService;
30 import org.opendaylight.mdsal.binding.api.RpcProviderService;
31 import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
32 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
33 import org.opendaylight.yangtools.util.xml.UntrustedXML;
34 import org.osgi.service.blueprint.container.ComponentDefinitionException;
35 import org.osgi.service.blueprint.reflect.BeanMetadata;
36 import org.osgi.service.blueprint.reflect.ComponentMetadata;
37 import org.osgi.service.blueprint.reflect.Metadata;
38 import org.osgi.service.blueprint.reflect.RefMetadata;
39 import org.osgi.service.blueprint.reflect.ReferenceMetadata;
40 import org.osgi.service.blueprint.reflect.ServiceMetadata;
41 import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
42 import org.osgi.service.blueprint.reflect.ValueMetadata;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Attr;
46 import org.w3c.dom.Element;
47 import org.w3c.dom.Node;
48 import org.w3c.dom.NodeList;
49 import org.xml.sax.InputSource;
50 import org.xml.sax.SAXException;
53 * The NamespaceHandler for Opendaylight blueprint extensions.
55 * @author Thomas Pantelis
57 public final class OpendaylightNamespaceHandler implements NamespaceHandler {
58 public static final String NAMESPACE_1_0_0 = "http://opendaylight.org/xmlns/blueprint/v1.0.0";
59 static final String ROUTED_RPC_REG_CONVERTER_NAME = "org.opendaylight.blueprint.RoutedRpcRegConverter";
60 static final String DOM_RPC_PROVIDER_SERVICE_NAME = "org.opendaylight.blueprint.DOMRpcProviderService";
61 static final String RPC_REGISTRY_NAME = "org.opendaylight.blueprint.RpcRegistry";
62 static final String BINDING_RPC_PROVIDER_SERVICE_NAME = "org.opendaylight.blueprint.RpcProviderService";
63 static final String SCHEMA_SERVICE_NAME = "org.opendaylight.blueprint.SchemaService";
64 static final String NOTIFICATION_SERVICE_NAME = "org.opendaylight.blueprint.NotificationService";
65 static final String TYPE_ATTR = "type";
66 static final String UPDATE_STRATEGY_ATTR = "update-strategy";
68 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightNamespaceHandler.class);
69 private static final String COMPONENT_PROCESSOR_NAME = ComponentProcessor.class.getName();
70 private static final String RESTART_DEPENDENTS_ON_UPDATES = "restart-dependents-on-updates";
71 private static final String USE_DEFAULT_FOR_REFERENCE_TYPES = "use-default-for-reference-types";
72 private static final String CLUSTERED_APP_CONFIG = "clustered-app-config";
73 private static final String INTERFACE = "interface";
74 private static final String REF_ATTR = "ref";
75 private static final String ID_ATTR = "id";
76 private static final String RPC_SERVICE = "rpc-service";
77 private static final String ACTION_SERVICE = "action-service";
78 private static final String SPECIFIC_SERVICE_REF_LIST = "specific-reference-list";
79 private static final String STATIC_REFERENCE = "static-reference";
81 @SuppressWarnings("rawtypes")
83 public Set<Class> getManagedClasses() {
84 return Collections.emptySet();
88 public URL getSchemaLocation(final String namespace) {
89 if (NAMESPACE_1_0_0.equals(namespace)) {
90 URL url = getClass().getResource("/opendaylight-blueprint-ext-1.0.0.xsd");
91 LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url);
99 public Metadata parse(final Element element, final ParserContext context) {
100 LOG.debug("In parse for {}", element);
102 if (nodeNameEquals(element, RpcImplementationBean.RPC_IMPLEMENTATION)) {
103 return parseRpcImplementation(element, context);
104 } else if (nodeNameEquals(element, RoutedRpcMetadata.ROUTED_RPC_IMPLEMENTATION)) {
105 return parseRoutedRpcImplementation(element, context);
106 } else if (nodeNameEquals(element, RPC_SERVICE)) {
107 return parseRpcService(element, context);
108 } else if (nodeNameEquals(element, NotificationListenerBean.NOTIFICATION_LISTENER)) {
109 return parseNotificationListener(element, context);
110 } else if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
111 return parseClusteredAppConfig(element, context);
112 } else if (nodeNameEquals(element, SPECIFIC_SERVICE_REF_LIST)) {
113 return parseSpecificReferenceList(element, context);
114 } else if (nodeNameEquals(element, STATIC_REFERENCE)) {
115 return parseStaticReference(element, context);
116 } else if (nodeNameEquals(element, ACTION_SERVICE)) {
117 return parseActionService(element, context);
118 } else if (nodeNameEquals(element, ActionProviderBean.ACTION_PROVIDER)) {
119 return parseActionProvider(element, context);
122 throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
126 public ComponentMetadata decorate(final Node node, final ComponentMetadata component, final ParserContext context) {
127 if (node instanceof Attr) {
128 if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) {
129 return decorateRestartDependentsOnUpdates((Attr) node, component, context);
130 } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) {
131 return decorateUseDefaultForReferenceTypes((Attr) node, component, context);
132 } else if (nodeNameEquals(node, TYPE_ATTR)) {
133 if (component instanceof ServiceReferenceMetadata) {
134 return decorateServiceReferenceType((Attr) node, component, context);
135 } else if (component instanceof ServiceMetadata) {
136 return decorateServiceType((Attr)node, component, context);
139 throw new ComponentDefinitionException("Attribute " + node.getNodeName()
140 + " can only be used on a <reference>, <reference-list> or <service> element");
143 throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
145 throw new ComponentDefinitionException("Unsupported node type: " + node);
149 private static ComponentMetadata decorateServiceType(final Attr attr, final ComponentMetadata component,
150 final ParserContext context) {
151 if (!(component instanceof MutableServiceMetadata)) {
152 throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
155 MutableServiceMetadata service = (MutableServiceMetadata)component;
157 LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
159 service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
163 @SuppressFBWarnings(value = "NP_NULL_PARAM_DEREF", justification = "Unrecognised NullableDecl")
164 private static ComponentMetadata decorateServiceReferenceType(final Attr attr, final ComponentMetadata component,
165 final ParserContext context) {
166 if (!(component instanceof MutableServiceReferenceMetadata)) {
167 throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
170 // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
171 // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
172 // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
173 // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
174 // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
175 // but as long as there's at least one processor registered, it correctly uses the extended filter.
176 registerComponentProcessor(context);
178 MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
179 String oldFilter = serviceRef.getExtendedFilter() == null ? null :
180 serviceRef.getExtendedFilter().getStringValue();
183 if (Strings.isNullOrEmpty(oldFilter)) {
184 filter = String.format("(type=%s)", attr.getValue());
186 filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
189 LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
190 serviceRef.getId(), attr.getValue(), oldFilter, filter);
192 serviceRef.setExtendedFilter(createValue(context, filter));
196 private static ComponentMetadata decorateRestartDependentsOnUpdates(final Attr attr,
197 final ComponentMetadata component, final ParserContext context) {
198 return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
201 private static ComponentMetadata decorateUseDefaultForReferenceTypes(final Attr attr,
202 final ComponentMetadata component, final ParserContext context) {
203 return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
206 private static ComponentMetadata enableComponentProcessorProperty(final Attr attr,
207 final ComponentMetadata component, final ParserContext context, final String propertyName) {
208 if (component != null) {
209 throw new ComponentDefinitionException("Attribute " + attr.getNodeName()
210 + " can only be used on the root <blueprint> element");
213 LOG.debug("{}: {}", propertyName, attr.getValue());
215 if (!Boolean.parseBoolean(attr.getValue())) {
219 MutableBeanMetadata metadata = registerComponentProcessor(context);
220 metadata.addProperty(propertyName, createValue(context, "true"));
225 private static MutableBeanMetadata registerComponentProcessor(final ParserContext context) {
226 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
227 MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
228 if (metadata == null) {
229 metadata = createBeanMetadata(context, COMPONENT_PROCESSOR_NAME, ComponentProcessor.class, false, true);
230 metadata.setProcessor(true);
231 addBlueprintBundleRefProperty(context, metadata);
232 metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
233 BlueprintContainerRestartService.class, null));
235 LOG.debug("Registering ComponentProcessor bean: {}", metadata);
237 registry.registerComponentDefinition(metadata);
243 private static Metadata parseActionProvider(final Element element, final ParserContext context) {
244 registerDomRpcProviderServiceRefBean(context);
245 registerBindingRpcProviderServiceRefBean(context);
246 registerSchemaServiceRefBean(context);
248 MutableBeanMetadata metadata = createBeanMetadata(context, context.generateId(), ActionProviderBean.class,
250 addBlueprintBundleRefProperty(context, metadata);
251 metadata.addProperty("domRpcProvider", createRef(context, DOM_RPC_PROVIDER_SERVICE_NAME));
252 metadata.addProperty("bindingRpcProvider", createRef(context, BINDING_RPC_PROVIDER_SERVICE_NAME));
253 metadata.addProperty("schemaService", createRef(context, SCHEMA_SERVICE_NAME));
254 metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
256 if (element.hasAttribute(REF_ATTR)) {
257 metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
260 LOG.debug("parseActionProvider returning {}", metadata);
265 private static Metadata parseRpcImplementation(final Element element, final ParserContext context) {
266 registerBindingRpcProviderServiceRefBean(context);
268 MutableBeanMetadata metadata = createBeanMetadata(context, context.generateId(), RpcImplementationBean.class,
270 addBlueprintBundleRefProperty(context, metadata);
271 metadata.addProperty("rpcProvider", createRef(context, BINDING_RPC_PROVIDER_SERVICE_NAME));
272 metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
274 if (element.hasAttribute(INTERFACE)) {
275 metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
278 LOG.debug("parseRpcImplementation returning {}", metadata);
282 private static Metadata parseRoutedRpcImplementation(final Element element, final ParserContext context) {
283 registerRefBean(context, RPC_REGISTRY_NAME, RpcProviderRegistry.class);
284 registerRoutedRpcRegistrationConverter(context);
286 ComponentFactoryMetadata metadata = new RoutedRpcMetadata(getId(context, element),
287 element.getAttribute(INTERFACE), element.getAttribute(REF_ATTR));
289 LOG.debug("parseRoutedRpcImplementation returning {}", metadata);
294 private static Metadata parseActionService(final Element element, final ParserContext context) {
295 ComponentFactoryMetadata metadata = new ActionServiceMetadata(getId(context, element),
296 element.getAttribute(INTERFACE));
298 LOG.debug("parseActionService returning {}", metadata);
303 private static Metadata parseRpcService(final Element element, final ParserContext context) {
304 ComponentFactoryMetadata metadata = new RpcServiceMetadata(getId(context, element),
305 element.getAttribute(INTERFACE));
307 LOG.debug("parseRpcService returning {}", metadata);
312 private static void registerRoutedRpcRegistrationConverter(final ParserContext context) {
313 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
314 if (registry.getComponentDefinition(ROUTED_RPC_REG_CONVERTER_NAME) == null) {
315 MutableBeanMetadata metadata = createBeanMetadata(context, ROUTED_RPC_REG_CONVERTER_NAME,
316 RoutedRpcRegistrationConverter.class, false, false);
317 metadata.setActivation(ReferenceMetadata.ACTIVATION_LAZY);
318 registry.registerTypeConverter(metadata);
322 private static void registerDomRpcProviderServiceRefBean(final ParserContext context) {
323 registerRefBean(context, DOM_RPC_PROVIDER_SERVICE_NAME, DOMRpcProviderService.class);
326 private static void registerBindingRpcProviderServiceRefBean(final ParserContext context) {
327 registerRefBean(context, BINDING_RPC_PROVIDER_SERVICE_NAME, RpcProviderService.class);
330 private static void registerSchemaServiceRefBean(final ParserContext context) {
331 registerRefBean(context, SCHEMA_SERVICE_NAME, DOMSchemaService.class);
334 private static void registerRefBean(final ParserContext context, final String name, final Class<?> clazz) {
335 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
336 if (registry.getComponentDefinition(name) == null) {
337 MutableReferenceMetadata metadata = createServiceRef(context, clazz, null);
338 metadata.setId(name);
339 registry.registerComponentDefinition(metadata);
343 private static Metadata parseNotificationListener(final Element element, final ParserContext context) {
344 registerNotificationServiceRefBean(context);
346 MutableBeanMetadata metadata = createBeanMetadata(context, context.generateId(), NotificationListenerBean.class,
348 addBlueprintBundleRefProperty(context, metadata);
349 metadata.addProperty("notificationService", createRef(context, NOTIFICATION_SERVICE_NAME));
350 metadata.addProperty("notificationListener", createRef(context, element.getAttribute(REF_ATTR)));
352 LOG.debug("parseNotificationListener returning {}", metadata);
357 private static void registerNotificationServiceRefBean(final ParserContext context) {
358 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
359 if (registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) {
360 MutableReferenceMetadata metadata = createServiceRef(context, NotificationService.class, null);
361 metadata.setId(NOTIFICATION_SERVICE_NAME);
362 registry.registerComponentDefinition(metadata);
366 private static Metadata parseClusteredAppConfig(final Element element, final ParserContext context) {
367 LOG.debug("parseClusteredAppConfig");
369 // Find the default-config child element representing the default app config XML, if present.
370 Element defaultConfigElement = null;
371 NodeList children = element.getChildNodes();
372 for (int i = 0; i < children.getLength(); i++) {
373 Node child = children.item(i);
374 if (nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
375 defaultConfigElement = (Element) child;
380 Element defaultAppConfigElement = null;
381 if (defaultConfigElement != null) {
382 // Find the CDATA element containing the default app config XML.
383 children = defaultConfigElement.getChildNodes();
384 for (int i = 0; i < children.getLength(); i++) {
385 Node child = children.item(i);
386 if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
387 defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG,
388 child.getTextContent());
394 return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
395 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
396 DataStoreAppConfigMetadata.LIST_KEY_VALUE), element.getAttribute(
397 DataStoreAppConfigMetadata.DEFAULT_CONFIG_FILE_NAME), parseUpdateStrategy(
398 element.getAttribute(UPDATE_STRATEGY_ATTR)), defaultAppConfigElement);
401 private static UpdateStrategy parseUpdateStrategy(final String updateStrategyValue) {
402 if (Strings.isNullOrEmpty(updateStrategyValue)
403 || updateStrategyValue.equalsIgnoreCase(UpdateStrategy.RELOAD.name())) {
404 return UpdateStrategy.RELOAD;
405 } else if (updateStrategyValue.equalsIgnoreCase(UpdateStrategy.NONE.name())) {
406 return UpdateStrategy.NONE;
408 LOG.warn("update-strategy {} not supported, using reload", updateStrategyValue);
409 return UpdateStrategy.RELOAD;
413 private static Metadata parseSpecificReferenceList(final Element element, final ParserContext context) {
414 ComponentFactoryMetadata metadata = new SpecificReferenceListMetadata(getId(context, element),
415 element.getAttribute(INTERFACE));
417 LOG.debug("parseSpecificReferenceList returning {}", metadata);
422 private static Metadata parseStaticReference(final Element element, final ParserContext context) {
423 ComponentFactoryMetadata metadata = new StaticReferenceMetadata(getId(context, element),
424 element.getAttribute(INTERFACE));
426 LOG.debug("parseStaticReference returning {}", metadata);
431 private static Element parseXML(final String name, final String xml) {
433 return UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
434 } catch (SAXException | IOException e) {
435 throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml), e);
439 private static ValueMetadata createValue(final ParserContext context, final String value) {
440 MutableValueMetadata metadata = context.createMetadata(MutableValueMetadata.class);
441 metadata.setStringValue(value);
445 private static MutableReferenceMetadata createServiceRef(final ParserContext context, final Class<?> cls,
446 final String filter) {
447 MutableReferenceMetadata metadata = context.createMetadata(MutableReferenceMetadata.class);
448 metadata.setRuntimeInterface(cls);
449 metadata.setInterface(cls.getName());
450 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
451 metadata.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
453 if (filter != null) {
454 metadata.setFilter(filter);
460 private static RefMetadata createRef(final ParserContext context, final String id) {
461 MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
462 metadata.setComponentId(id);
466 private static String getId(final ParserContext context, final Element element) {
467 if (element.hasAttribute(ID_ATTR)) {
468 return element.getAttribute(ID_ATTR);
470 return context.generateId();
474 private static boolean nodeNameEquals(final Node node, final String name) {
475 return name.equals(node.getNodeName()) || name.equals(node.getLocalName());
478 private static void addBlueprintBundleRefProperty(final ParserContext context, final MutableBeanMetadata metadata) {
479 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
482 private static MutableBeanMetadata createBeanMetadata(final ParserContext context, final String id,
483 final Class<?> runtimeClass, final boolean initMethod, final boolean destroyMethod) {
484 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
486 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
487 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
488 metadata.setRuntimeClass(runtimeClass);
491 metadata.setInitMethod("init");
495 metadata.setDestroyMethod("destroy");