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 java.io.IOException;
12 import java.io.StringReader;
14 import java.util.Collections;
16 import javax.xml.parsers.DocumentBuilderFactory;
17 import javax.xml.parsers.ParserConfigurationException;
18 import org.apache.aries.blueprint.ComponentDefinitionRegistry;
19 import org.apache.aries.blueprint.NamespaceHandler;
20 import org.apache.aries.blueprint.ParserContext;
21 import org.apache.aries.blueprint.ext.ComponentFactoryMetadata;
22 import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
23 import org.apache.aries.blueprint.mutable.MutableRefMetadata;
24 import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
25 import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
26 import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
27 import org.apache.aries.blueprint.mutable.MutableValueMetadata;
28 import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
29 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
30 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
31 import org.osgi.service.blueprint.container.ComponentDefinitionException;
32 import org.osgi.service.blueprint.reflect.BeanMetadata;
33 import org.osgi.service.blueprint.reflect.ComponentMetadata;
34 import org.osgi.service.blueprint.reflect.Metadata;
35 import org.osgi.service.blueprint.reflect.RefMetadata;
36 import org.osgi.service.blueprint.reflect.ReferenceMetadata;
37 import org.osgi.service.blueprint.reflect.ServiceMetadata;
38 import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
39 import org.osgi.service.blueprint.reflect.ValueMetadata;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.w3c.dom.Attr;
43 import org.w3c.dom.Element;
44 import org.w3c.dom.Node;
45 import org.w3c.dom.NodeList;
46 import org.xml.sax.InputSource;
47 import org.xml.sax.SAXException;
50 * The NamespaceHandler for Opendaylight blueprint extensions.
52 * @author Thomas Pantelis
54 public class OpendaylightNamespaceHandler implements NamespaceHandler {
55 public static final String NAMESPACE_1_0_0 = "http://opendaylight.org/xmlns/blueprint/v1.0.0";
56 static final String ROUTED_RPC_REG_CONVERTER_NAME = "org.opendaylight.blueprint.RoutedRpcRegConverter";
57 static final String RPC_REGISTRY_NAME = "org.opendaylight.blueprint.RpcRegistry";
58 static final String NOTIFICATION_SERVICE_NAME = "org.opendaylight.blueprint.NotificationService";
59 static final String TYPE_ATTR = "type";
60 static final String UPDATE_STRATEGY_ATTR = "update-strategy";
62 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightNamespaceHandler.class);
63 private static final String COMPONENT_PROCESSOR_NAME = ComponentProcessor.class.getName();
64 private static final String RESTART_DEPENDENTS_ON_UPDATES = "restart-dependents-on-updates";
65 private static final String USE_DEFAULT_FOR_REFERENCE_TYPES = "use-default-for-reference-types";
66 private static final String CLUSTERED_APP_CONFIG = "clustered-app-config";
67 private static final String INTERFACE = "interface";
68 private static final String REF_ATTR = "ref";
69 private static final String ID_ATTR = "id";
70 private static final String RPC_SERVICE = "rpc-service";
71 private static final String SPECIFIC_SERVICE_REF_LIST = "specific-reference-list";
72 private static final String STATIC_REFERENCE = "static-reference";
74 @SuppressWarnings("rawtypes")
76 public Set<Class> getManagedClasses() {
77 return Collections.emptySet();
81 public URL getSchemaLocation(String namespace) {
82 if (NAMESPACE_1_0_0.equals(namespace)) {
83 URL url = getClass().getResource("/opendaylight-blueprint-ext-1.0.0.xsd");
84 LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url);
92 public Metadata parse(Element element, ParserContext context) {
93 LOG.debug("In parse for {}", element);
95 if (nodeNameEquals(element, RpcImplementationBean.RPC_IMPLEMENTATION)) {
96 return parseRpcImplementation(element, context);
97 } else if (nodeNameEquals(element, RoutedRpcMetadata.ROUTED_RPC_IMPLEMENTATION)) {
98 return parseRoutedRpcImplementation(element, context);
99 } else if (nodeNameEquals(element, RPC_SERVICE)) {
100 return parseRpcService(element, context);
101 } else if (nodeNameEquals(element, NotificationListenerBean.NOTIFICATION_LISTENER)) {
102 return parseNotificationListener(element, context);
103 } else if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
104 return parseClusteredAppConfig(element, context);
105 } else if (nodeNameEquals(element, SPECIFIC_SERVICE_REF_LIST)) {
106 return parseSpecificReferenceList(element, context);
107 } else if (nodeNameEquals(element, STATIC_REFERENCE)) {
108 return parseStaticReference(element, context);
111 throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
115 public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
116 if (node instanceof Attr) {
117 if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) {
118 return decorateRestartDependentsOnUpdates((Attr) node, component, context);
119 } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) {
120 return decorateUseDefaultForReferenceTypes((Attr) node, component, context);
121 } else if (nodeNameEquals(node, TYPE_ATTR)) {
122 if (component instanceof ServiceReferenceMetadata) {
123 return decorateServiceReferenceType((Attr) node, component, context);
124 } else if (component instanceof ServiceMetadata) {
125 return decorateServiceType((Attr)node, component, context);
128 throw new ComponentDefinitionException("Attribute " + node.getNodeName()
129 + " can only be used on a <reference>, <reference-list> or <service> element");
132 throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
134 throw new ComponentDefinitionException("Unsupported node type: " + node);
138 private ComponentMetadata decorateServiceType(Attr attr, ComponentMetadata component, ParserContext context) {
139 if (!(component instanceof MutableServiceMetadata)) {
140 throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
143 MutableServiceMetadata service = (MutableServiceMetadata)component;
145 LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
147 service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
151 private ComponentMetadata decorateServiceReferenceType(Attr attr, ComponentMetadata component,
152 ParserContext context) {
153 if (!(component instanceof MutableServiceReferenceMetadata)) {
154 throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
157 // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
158 // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
159 // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
160 // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
161 // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
162 // but as long as there's at least one processor registered, it correctly uses the extended filter.
163 registerComponentProcessor(context);
165 MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
166 String oldFilter = serviceRef.getExtendedFilter() == null ? null :
167 serviceRef.getExtendedFilter().getStringValue();
170 if (Strings.isNullOrEmpty(oldFilter)) {
171 filter = String.format("(type=%s)", attr.getValue());
173 filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
176 LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
177 serviceRef.getId(), attr.getValue(), oldFilter, filter);
179 serviceRef.setExtendedFilter(createValue(context, filter));
183 private static ComponentMetadata decorateRestartDependentsOnUpdates(Attr attr, ComponentMetadata component,
184 ParserContext context) {
185 return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
188 private static ComponentMetadata decorateUseDefaultForReferenceTypes(Attr attr, ComponentMetadata component,
189 ParserContext context) {
190 return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
193 private static ComponentMetadata enableComponentProcessorProperty(Attr attr, ComponentMetadata component,
194 ParserContext context, String propertyName) {
195 if (component != null) {
196 throw new ComponentDefinitionException("Attribute " + attr.getNodeName()
197 + " can only be used on the root <blueprint> element");
200 LOG.debug("{}: {}", propertyName, attr.getValue());
202 if (!Boolean.parseBoolean(attr.getValue())) {
206 MutableBeanMetadata metadata = registerComponentProcessor(context);
207 metadata.addProperty(propertyName, createValue(context, "true"));
212 private static MutableBeanMetadata registerComponentProcessor(ParserContext context) {
213 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
214 MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
215 if (metadata == null) {
216 metadata = context.createMetadata(MutableBeanMetadata.class);
217 metadata.setProcessor(true);
218 metadata.setId(COMPONENT_PROCESSOR_NAME);
219 metadata.setActivation(BeanMetadata.ACTIVATION_EAGER);
220 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
221 metadata.setRuntimeClass(ComponentProcessor.class);
222 metadata.setDestroyMethod("destroy");
223 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
224 metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
225 BlueprintContainerRestartService.class, null));
227 LOG.debug("Registering ComponentProcessor bean: {}", metadata);
229 registry.registerComponentDefinition(metadata);
235 private Metadata parseRpcImplementation(Element element, ParserContext context) {
236 registerRpcRegistryServiceRefBean(context);
238 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
239 metadata.setId(context.generateId());
240 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
241 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
242 metadata.setRuntimeClass(RpcImplementationBean.class);
243 metadata.setInitMethod("init");
244 metadata.setDestroyMethod("destroy");
245 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
246 metadata.addProperty("rpcRegistry", createRef(context, RPC_REGISTRY_NAME));
247 metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
249 if (element.hasAttribute(INTERFACE)) {
250 metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
253 LOG.debug("parseAddRpcImplementation returning {}", metadata);
258 private Metadata parseRoutedRpcImplementation(Element element, ParserContext context) {
259 registerRpcRegistryServiceRefBean(context);
260 registerRoutedRpcRegistrationConverter(context);
262 ComponentFactoryMetadata metadata = new RoutedRpcMetadata(getId(context, element),
263 element.getAttribute(INTERFACE), element.getAttribute(REF_ATTR));
265 LOG.debug("parseRoutedRpcImplementation returning {}", metadata);
270 private Metadata parseRpcService(Element element, ParserContext context) {
271 ComponentFactoryMetadata metadata = new RpcServiceMetadata(getId(context, element),
272 element.getAttribute(INTERFACE));
274 LOG.debug("parseRpcService returning {}", metadata);
279 private void registerRoutedRpcRegistrationConverter(ParserContext context) {
280 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
281 if (registry.getComponentDefinition(ROUTED_RPC_REG_CONVERTER_NAME) == null) {
282 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
283 metadata.setId(ROUTED_RPC_REG_CONVERTER_NAME);
284 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
285 metadata.setActivation(ReferenceMetadata.ACTIVATION_LAZY);
286 metadata.setRuntimeClass(RoutedRpcRegistrationConverter.class);
287 registry.registerTypeConverter(metadata);
291 private void registerRpcRegistryServiceRefBean(ParserContext context) {
292 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
293 if (registry.getComponentDefinition(RPC_REGISTRY_NAME) == null) {
294 MutableReferenceMetadata metadata = createServiceRef(context, RpcProviderRegistry.class, null);
295 metadata.setId(RPC_REGISTRY_NAME);
296 registry.registerComponentDefinition(metadata);
300 private Metadata parseNotificationListener(Element element, ParserContext context) {
301 registerNotificationServiceRefBean(context);
303 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
304 metadata.setId(context.generateId());
305 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
306 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
307 metadata.setRuntimeClass(NotificationListenerBean.class);
308 metadata.setInitMethod("init");
309 metadata.setDestroyMethod("destroy");
310 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
311 metadata.addProperty("notificationService", createRef(context, NOTIFICATION_SERVICE_NAME));
312 metadata.addProperty("notificationListener", createRef(context, element.getAttribute(REF_ATTR)));
314 LOG.debug("parseNotificationListener returning {}", metadata);
319 private void registerNotificationServiceRefBean(ParserContext context) {
320 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
321 if (registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) {
322 MutableReferenceMetadata metadata = createServiceRef(context, NotificationService.class, null);
323 metadata.setId(NOTIFICATION_SERVICE_NAME);
324 registry.registerComponentDefinition(metadata);
328 private Metadata parseClusteredAppConfig(Element element, ParserContext context) {
329 LOG.debug("parseClusteredAppConfig");
331 // Find the default-config child element representing the default app config XML, if present.
332 Element defaultConfigElement = null;
333 NodeList children = element.getChildNodes();
334 for (int i = 0; i < children.getLength(); i++) {
335 Node child = children.item(i);
336 if (nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
337 defaultConfigElement = (Element) child;
342 Element defaultAppConfigElement = null;
343 if (defaultConfigElement != null) {
344 // Find the CDATA element containing the default app config XML.
345 children = defaultConfigElement.getChildNodes();
346 for (int i = 0; i < children.getLength(); i++) {
347 Node child = children.item(i);
348 if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
349 defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG,
350 child.getTextContent());
356 return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
357 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
358 DataStoreAppConfigMetadata.LIST_KEY_VALUE), element.getAttribute(
359 DataStoreAppConfigMetadata.DEFAULT_CONFIG_FILE_NAME), parseUpdateStrategy(
360 element.getAttribute(UPDATE_STRATEGY_ATTR)), defaultAppConfigElement);
363 private UpdateStrategy parseUpdateStrategy(String updateStrategyValue) {
364 if (Strings.isNullOrEmpty(updateStrategyValue)
365 || updateStrategyValue.equalsIgnoreCase(UpdateStrategy.RELOAD.name())) {
366 return UpdateStrategy.RELOAD;
367 } else if (updateStrategyValue.equalsIgnoreCase(UpdateStrategy.NONE.name())) {
368 return UpdateStrategy.NONE;
370 LOG.warn("update-strategy {} not supported, using reload", updateStrategyValue);
371 return UpdateStrategy.RELOAD;
375 private Metadata parseSpecificReferenceList(Element element, ParserContext context) {
376 ComponentFactoryMetadata metadata = new SpecificReferenceListMetadata(getId(context, element),
377 element.getAttribute(INTERFACE));
379 LOG.debug("parseSpecificReferenceList returning {}", metadata);
384 private Metadata parseStaticReference(Element element, ParserContext context) {
385 ComponentFactoryMetadata metadata = new StaticReferenceMetadata(getId(context, element),
386 element.getAttribute(INTERFACE));
388 LOG.debug("parseStaticReference returning {}", metadata);
393 private Element parseXML(String name, String xml) {
394 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
395 builderFactory.setNamespaceAware(true);
396 builderFactory.setCoalescing(true);
397 builderFactory.setIgnoringElementContentWhitespace(true);
398 builderFactory.setIgnoringComments(true);
401 return builderFactory.newDocumentBuilder().parse(new InputSource(
402 new StringReader(xml))).getDocumentElement();
403 } catch (SAXException | IOException | ParserConfigurationException e) {
404 throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml), e);
408 private static ValueMetadata createValue(ParserContext context, String value) {
409 MutableValueMetadata metadata = context.createMetadata(MutableValueMetadata.class);
410 metadata.setStringValue(value);
414 private static MutableReferenceMetadata createServiceRef(ParserContext context, Class<?> cls, String filter) {
415 MutableReferenceMetadata metadata = context.createMetadata(MutableReferenceMetadata.class);
416 metadata.setRuntimeInterface(cls);
417 metadata.setInterface(cls.getName());
418 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
419 metadata.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
421 if (filter != null) {
422 metadata.setFilter(filter);
428 private static RefMetadata createRef(ParserContext context, String id) {
429 MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
430 metadata.setComponentId(id);
434 private static String getId(ParserContext context, Element element) {
435 if (element.hasAttribute(ID_ATTR)) {
436 return element.getAttribute(ID_ATTR);
438 return context.generateId();
442 private static boolean nodeNameEquals(Node node, String name) {
443 return name.equals(node.getNodeName()) || name.equals(node.getLocalName());