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.StringReader;
13 import java.util.Collections;
15 import javax.xml.parsers.DocumentBuilderFactory;
16 import org.apache.aries.blueprint.ComponentDefinitionRegistry;
17 import org.apache.aries.blueprint.NamespaceHandler;
18 import org.apache.aries.blueprint.ParserContext;
19 import org.apache.aries.blueprint.ext.ComponentFactoryMetadata;
20 import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
21 import org.apache.aries.blueprint.mutable.MutableRefMetadata;
22 import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
23 import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
24 import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
25 import org.apache.aries.blueprint.mutable.MutableValueMetadata;
26 import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
27 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
28 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
29 import org.osgi.service.blueprint.container.ComponentDefinitionException;
30 import org.osgi.service.blueprint.reflect.BeanMetadata;
31 import org.osgi.service.blueprint.reflect.ComponentMetadata;
32 import org.osgi.service.blueprint.reflect.Metadata;
33 import org.osgi.service.blueprint.reflect.RefMetadata;
34 import org.osgi.service.blueprint.reflect.ReferenceMetadata;
35 import org.osgi.service.blueprint.reflect.ServiceMetadata;
36 import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
37 import org.osgi.service.blueprint.reflect.ValueMetadata;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.w3c.dom.Attr;
41 import org.w3c.dom.Element;
42 import org.w3c.dom.Node;
43 import org.w3c.dom.NodeList;
44 import org.xml.sax.InputSource;
47 * The NamespaceHandler for Opendaylight blueprint extensions.
49 * @author Thomas Pantelis
51 public class OpendaylightNamespaceHandler implements NamespaceHandler {
52 public static final String NAMESPACE_1_0_0 = "http://opendaylight.org/xmlns/blueprint/v1.0.0";
53 static final String ROUTED_RPC_REG_CONVERTER_NAME = "org.opendaylight.blueprint.RoutedRpcRegConverter";
54 static final String RPC_REGISTRY_NAME = "org.opendaylight.blueprint.RpcRegistry";
55 static final String NOTIFICATION_SERVICE_NAME = "org.opendaylight.blueprint.NotificationService";
56 static final String TYPE_ATTR = "type";
58 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightNamespaceHandler.class);
59 private static final String COMPONENT_PROCESSOR_NAME = ComponentProcessor.class.getName();
60 private static final String RESTART_DEPENDENTS_ON_UPDATES = "restart-dependents-on-updates";
61 private static final String USE_DEFAULT_FOR_REFERENCE_TYPES = "use-default-for-reference-types";
62 private static final String CLUSTERED_APP_CONFIG = "clustered-app-config";
63 private static final String INTERFACE = "interface";
64 private static final String REF_ATTR = "ref";
65 private static final String ID_ATTR = "id";
66 private static final String RPC_SERVICE = "rpc-service";
67 private static final String SPECIFIC_SERVICE_REF_LIST = "specific-reference-list";
68 private static final String STATIC_REFERENCE = "static-reference";
70 @SuppressWarnings("rawtypes")
72 public Set<Class> getManagedClasses() {
73 return Collections.emptySet();
77 public URL getSchemaLocation(String namespace) {
78 if(NAMESPACE_1_0_0.equals(namespace)) {
79 URL url = getClass().getResource("/opendaylight-blueprint-ext-1.0.0.xsd");
80 LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url);
88 public Metadata parse(Element element, ParserContext context) {
89 LOG.debug("In parse for {}", element);
91 if (nodeNameEquals(element, RpcImplementationBean.RPC_IMPLEMENTATION)) {
92 return parseRpcImplementation(element, context);
93 } else if (nodeNameEquals(element, RoutedRpcMetadata.ROUTED_RPC_IMPLEMENTATION)) {
94 return parseRoutedRpcImplementation(element, context);
95 } else if (nodeNameEquals(element, RPC_SERVICE)) {
96 return parseRpcService(element, context);
97 } else if (nodeNameEquals(element, NotificationListenerBean.NOTIFICATION_LISTENER)) {
98 return parseNotificationListener(element, context);
99 } else if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
100 return parseClusteredAppConfig(element, context);
101 } else if (nodeNameEquals(element, SPECIFIC_SERVICE_REF_LIST)) {
102 return parseSpecificReferenceList(element, context);
103 } else if (nodeNameEquals(element, STATIC_REFERENCE)) {
104 return parseStaticReference(element, context);
107 throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
111 public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
112 if(node instanceof Attr) {
113 if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) {
114 return decorateRestartDependentsOnUpdates((Attr)node, component, context);
115 } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) {
116 return decorateUseDefaultForReferenceTypes((Attr)node, component, context);
117 } else if (nodeNameEquals(node, TYPE_ATTR)) {
118 if(component instanceof ServiceReferenceMetadata) {
119 return decorateServiceReferenceType((Attr)node, component, context);
120 } else if(component instanceof ServiceMetadata) {
121 return decorateServiceType((Attr)node, component, context);
124 throw new ComponentDefinitionException("Attribute " + node.getNodeName() +
125 " can only be used on a <reference>, <reference-list> or <service> element");
128 throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
130 throw new ComponentDefinitionException("Unsupported node type: " + node);
134 private ComponentMetadata decorateServiceType(Attr attr, ComponentMetadata component, ParserContext context) {
135 if (!(component instanceof MutableServiceMetadata)) {
136 throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
139 MutableServiceMetadata service = (MutableServiceMetadata)component;
141 LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
143 service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
147 private ComponentMetadata decorateServiceReferenceType(Attr attr, ComponentMetadata component, ParserContext context) {
148 if (!(component instanceof MutableServiceReferenceMetadata)) {
149 throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
152 // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
153 // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
154 // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
155 // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
156 // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
157 // but as long as there's at least one processor registered, it correctly uses the extended filter.
158 registerComponentProcessor(context);
160 MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
161 String oldFilter = serviceRef.getExtendedFilter() == null ? null :
162 serviceRef.getExtendedFilter().getStringValue();
165 if(Strings.isNullOrEmpty(oldFilter)) {
166 filter = String.format("(type=%s)", attr.getValue());
168 filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
171 LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
172 serviceRef.getId(), attr.getValue(), oldFilter, filter);
174 serviceRef.setExtendedFilter(createValue(context, filter));
178 private static ComponentMetadata decorateRestartDependentsOnUpdates(Attr attr, ComponentMetadata component,
179 ParserContext context) {
180 return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
183 private static ComponentMetadata decorateUseDefaultForReferenceTypes(Attr attr, ComponentMetadata component,
184 ParserContext context) {
185 return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
188 private static ComponentMetadata enableComponentProcessorProperty(Attr attr, ComponentMetadata component,
189 ParserContext context, String propertyName) {
190 if(component != null) {
191 throw new ComponentDefinitionException("Attribute " + attr.getNodeName() +
192 " can only be used on the root <blueprint> element");
195 LOG.debug("{}: {}", propertyName, attr.getValue());
197 if(!Boolean.parseBoolean(attr.getValue())) {
201 MutableBeanMetadata metadata = registerComponentProcessor(context);
202 metadata.addProperty(propertyName, createValue(context, "true"));
207 private static MutableBeanMetadata registerComponentProcessor(ParserContext context) {
208 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
209 MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
210 if(metadata == null) {
211 metadata = context.createMetadata(MutableBeanMetadata.class);
212 metadata.setProcessor(true);
213 metadata.setId(COMPONENT_PROCESSOR_NAME);
214 metadata.setActivation(BeanMetadata.ACTIVATION_EAGER);
215 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
216 metadata.setRuntimeClass(ComponentProcessor.class);
217 metadata.setDestroyMethod("destroy");
218 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
219 metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
220 BlueprintContainerRestartService.class, null));
222 LOG.debug("Registering ComponentProcessor bean: {}", metadata);
224 registry.registerComponentDefinition(metadata);
230 private Metadata parseRpcImplementation(Element element, ParserContext context) {
231 registerRpcRegistryServiceRefBean(context);
233 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
234 metadata.setId(context.generateId());
235 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
236 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
237 metadata.setRuntimeClass(RpcImplementationBean.class);
238 metadata.setInitMethod("init");
239 metadata.setDestroyMethod("destroy");
240 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
241 metadata.addProperty("rpcRegistry", createRef(context, RPC_REGISTRY_NAME));
242 metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
244 if(element.hasAttribute(INTERFACE)) {
245 metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
248 LOG.debug("parseAddRpcImplementation returning {}", metadata);
253 private Metadata parseRoutedRpcImplementation(Element element, ParserContext context) {
254 registerRpcRegistryServiceRefBean(context);
255 registerRoutedRpcRegistrationConverter(context);
257 ComponentFactoryMetadata metadata = new RoutedRpcMetadata(getId(context, element),
258 element.getAttribute(INTERFACE), element.getAttribute(REF_ATTR));
260 LOG.debug("parseRoutedRpcImplementation returning {}", metadata);
265 private Metadata parseRpcService(Element element, ParserContext context) {
266 ComponentFactoryMetadata metadata = new RpcServiceMetadata(getId(context, element),
267 element.getAttribute(INTERFACE));
269 LOG.debug("parseRpcService returning {}", metadata);
274 private void registerRoutedRpcRegistrationConverter(ParserContext context) {
275 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
276 if(registry.getComponentDefinition(ROUTED_RPC_REG_CONVERTER_NAME) == null) {
277 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
278 metadata.setId(ROUTED_RPC_REG_CONVERTER_NAME);
279 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
280 metadata.setActivation(ReferenceMetadata.ACTIVATION_LAZY);
281 metadata.setRuntimeClass(RoutedRpcRegistrationConverter.class);
282 registry.registerTypeConverter(metadata);
286 private void registerRpcRegistryServiceRefBean(ParserContext context) {
287 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
288 if(registry.getComponentDefinition(RPC_REGISTRY_NAME) == null) {
289 MutableReferenceMetadata metadata = createServiceRef(context, RpcProviderRegistry.class, null);
290 metadata.setId(RPC_REGISTRY_NAME);
291 registry.registerComponentDefinition(metadata);
295 private Metadata parseNotificationListener(Element element, ParserContext context) {
296 registerNotificationServiceRefBean(context);
298 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
299 metadata.setId(context.generateId());
300 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
301 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
302 metadata.setRuntimeClass(NotificationListenerBean.class);
303 metadata.setInitMethod("init");
304 metadata.setDestroyMethod("destroy");
305 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
306 metadata.addProperty("notificationService", createRef(context, NOTIFICATION_SERVICE_NAME));
307 metadata.addProperty("notificationListener", createRef(context, element.getAttribute(REF_ATTR)));
309 LOG.debug("parseNotificationListener returning {}", metadata);
314 private void registerNotificationServiceRefBean(ParserContext context) {
315 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
316 if(registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) {
317 MutableReferenceMetadata metadata = createServiceRef(context, NotificationService.class, null);
318 metadata.setId(NOTIFICATION_SERVICE_NAME);
319 registry.registerComponentDefinition(metadata);
323 private Metadata parseClusteredAppConfig(Element element, ParserContext context) {
324 LOG.debug("parseClusteredAppConfig");
326 // Find the default-config child element representing the default app config XML, if present.
327 Element defaultConfigElement = null;
328 NodeList children = element.getChildNodes();
329 for(int i = 0; i < children.getLength(); i++) {
330 Node child = children.item(i);
331 if(nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
332 defaultConfigElement = (Element) child;
337 Element defaultAppConfigElement = null;
338 if(defaultConfigElement != null) {
339 // Find the CDATA element containing the default app config XML.
340 children = defaultConfigElement.getChildNodes();
341 for(int i = 0; i < children.getLength(); i++) {
342 Node child = children.item(i);
343 if(child.getNodeType() == Node.CDATA_SECTION_NODE) {
344 defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG, child.getTextContent());
350 return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
351 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
352 DataStoreAppConfigMetadata.LIST_KEY_VALUE), element.getAttribute(
353 DataStoreAppConfigMetadata.DEFAULT_CONFIG_FILE_NAME), defaultAppConfigElement);
356 private Metadata parseSpecificReferenceList(Element element, ParserContext context) {
357 ComponentFactoryMetadata metadata = new SpecificReferenceListMetadata(getId(context, element),
358 element.getAttribute(INTERFACE));
360 LOG.debug("parseSpecificReferenceList returning {}", metadata);
365 private Metadata parseStaticReference(Element element, ParserContext context) {
366 ComponentFactoryMetadata metadata = new StaticReferenceMetadata(getId(context, element),
367 element.getAttribute(INTERFACE));
369 LOG.debug("parseStaticReference returning {}", metadata);
374 private Element parseXML(String name, String xml) {
375 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
376 builderFactory.setNamespaceAware(true);
377 builderFactory.setCoalescing(true);
378 builderFactory.setIgnoringElementContentWhitespace(true);
379 builderFactory.setIgnoringComments(true);
382 return builderFactory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
383 } catch(Exception e) {
384 throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml));
388 private static ValueMetadata createValue(ParserContext context, String value) {
389 MutableValueMetadata m = context.createMetadata(MutableValueMetadata.class);
390 m.setStringValue(value);
394 private static MutableReferenceMetadata createServiceRef(ParserContext context, Class<?> cls, String filter) {
395 MutableReferenceMetadata m = context.createMetadata(MutableReferenceMetadata.class);
396 m.setRuntimeInterface(cls);
397 m.setInterface(cls.getName());
398 m.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
399 m.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
408 private static RefMetadata createRef(ParserContext context, String id) {
409 MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
410 metadata.setComponentId(id);
414 private static String getId(ParserContext context, Element element) {
415 if(element.hasAttribute(ID_ATTR)) {
416 return element.getAttribute(ID_ATTR);
418 return context.generateId();
422 private static boolean nodeNameEquals(Node node, String name) {
423 return name.equals(node.getNodeName()) || name.equals(node.getLocalName());