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";
57 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightNamespaceHandler.class);
58 private static final String COMPONENT_PROCESSOR_NAME = ComponentProcessor.class.getName();
59 private static final String RESTART_DEPENDENTS_ON_UPDATES = "restart-dependents-on-updates";
60 private static final String USE_DEFAULT_FOR_REFERENCE_TYPES = "use-default-for-reference-types";
61 private static final String CLUSTERED_APP_CONFIG = "clustered-app-config";
62 private static final String TYPE_ATTR = "type";
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";
68 @SuppressWarnings("rawtypes")
70 public Set<Class> getManagedClasses() {
71 return Collections.emptySet();
75 public URL getSchemaLocation(String namespace) {
76 if(NAMESPACE_1_0_0.equals(namespace)) {
77 URL url = getClass().getResource("/opendaylight-blueprint-ext-1.0.0.xsd");
78 LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url);
86 public Metadata parse(Element element, ParserContext context) {
87 LOG.debug("In parse for {}", element);
89 if (nodeNameEquals(element, RpcImplementationBean.RPC_IMPLEMENTATION)) {
90 return parseRpcImplementation(element, context);
91 } else if (nodeNameEquals(element, RoutedRpcMetadata.ROUTED_RPC_IMPLEMENTATION)) {
92 return parseRoutedRpcImplementation(element, context);
93 } else if (nodeNameEquals(element, RPC_SERVICE)) {
94 return parseRpcService(element, context);
95 } else if (nodeNameEquals(element, NotificationListenerBean.NOTIFICATION_LISTENER)) {
96 return parseNotificationListener(element, context);
97 } else if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
98 return parseClusteredAppConfig(element, context);
101 throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
105 public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
106 if(node instanceof Attr) {
107 if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) {
108 return decorateRestartDependentsOnUpdates((Attr)node, component, context);
109 } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) {
110 return decorateUseDefaultForReferenceTypes((Attr)node, component, context);
111 } else if (nodeNameEquals(node, TYPE_ATTR)) {
112 if(component instanceof ServiceReferenceMetadata) {
113 return decorateServiceReferenceType((Attr)node, component, context);
114 } else if(component instanceof ServiceMetadata) {
115 return decorateServiceType((Attr)node, component, context);
118 throw new ComponentDefinitionException("Attribute " + node.getNodeName() +
119 " can only be used on a <reference>, <reference-list> or <service> element");
122 throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
124 throw new ComponentDefinitionException("Unsupported node type: " + node);
128 private ComponentMetadata decorateServiceType(Attr attr, ComponentMetadata component, ParserContext context) {
129 if (!(component instanceof MutableServiceMetadata)) {
130 throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
133 MutableServiceMetadata service = (MutableServiceMetadata)component;
135 LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
137 service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
141 private ComponentMetadata decorateServiceReferenceType(Attr attr, ComponentMetadata component, ParserContext context) {
142 if (!(component instanceof MutableServiceReferenceMetadata)) {
143 throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
146 // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
147 // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
148 // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
149 // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
150 // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
151 // but as long as there's at least one processor registered, it correctly uses the extended filter.
152 registerComponentProcessor(context);
154 MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
155 String oldFilter = serviceRef.getExtendedFilter() == null ? null :
156 serviceRef.getExtendedFilter().getStringValue();
159 if(Strings.isNullOrEmpty(oldFilter)) {
160 filter = String.format("(type=%s)", attr.getValue());
162 filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
165 LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
166 serviceRef.getId(), attr.getValue(), oldFilter, filter);
168 serviceRef.setExtendedFilter(createValue(context, filter));
172 private static ComponentMetadata decorateRestartDependentsOnUpdates(Attr attr, ComponentMetadata component,
173 ParserContext context) {
174 return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
177 private static ComponentMetadata decorateUseDefaultForReferenceTypes(Attr attr, ComponentMetadata component,
178 ParserContext context) {
179 return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
182 private static ComponentMetadata enableComponentProcessorProperty(Attr attr, ComponentMetadata component,
183 ParserContext context, String propertyName) {
184 if(component != null) {
185 throw new ComponentDefinitionException("Attribute " + attr.getNodeName() +
186 " can only be used on the root <blueprint> element");
189 LOG.debug("{}: {}", propertyName, attr.getValue());
191 if(!Boolean.parseBoolean(attr.getValue())) {
195 MutableBeanMetadata metadata = registerComponentProcessor(context);
196 metadata.addProperty(propertyName, createValue(context, "true"));
201 private static MutableBeanMetadata registerComponentProcessor(ParserContext context) {
202 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
203 MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
204 if(metadata == null) {
205 metadata = context.createMetadata(MutableBeanMetadata.class);
206 metadata.setProcessor(true);
207 metadata.setId(COMPONENT_PROCESSOR_NAME);
208 metadata.setActivation(BeanMetadata.ACTIVATION_EAGER);
209 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
210 metadata.setRuntimeClass(ComponentProcessor.class);
211 metadata.setDestroyMethod("destroy");
212 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
213 metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
214 BlueprintContainerRestartService.class, null));
216 LOG.debug("Registering ComponentProcessor bean: {}", metadata);
218 registry.registerComponentDefinition(metadata);
224 private Metadata parseRpcImplementation(Element element, ParserContext context) {
225 registerRpcRegistryServiceRefBean(context);
227 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
228 metadata.setId(context.generateId());
229 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
230 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
231 metadata.setRuntimeClass(RpcImplementationBean.class);
232 metadata.setInitMethod("init");
233 metadata.setDestroyMethod("destroy");
234 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
235 metadata.addProperty("rpcRegistry", createRef(context, RPC_REGISTRY_NAME));
236 metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
238 if(element.hasAttribute(INTERFACE)) {
239 metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
242 LOG.debug("parseAddRpcImplementation returning {}", metadata);
247 private Metadata parseRoutedRpcImplementation(Element element, ParserContext context) {
248 registerRpcRegistryServiceRefBean(context);
249 registerRoutedRpcRegistrationConverter(context);
251 ComponentFactoryMetadata metadata = new RoutedRpcMetadata(getId(context, element),
252 element.getAttribute(INTERFACE), element.getAttribute(REF_ATTR));
254 LOG.debug("parseRoutedRpcImplementation returning {}", metadata);
259 private Metadata parseRpcService(Element element, ParserContext context) {
260 ComponentFactoryMetadata metadata = new RpcServiceMetadata(getId(context, element),
261 element.getAttribute(INTERFACE));
263 LOG.debug("parseRpcService returning {}", metadata);
268 private void registerRoutedRpcRegistrationConverter(ParserContext context) {
269 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
270 if(registry.getComponentDefinition(ROUTED_RPC_REG_CONVERTER_NAME) == null) {
271 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
272 metadata.setId(ROUTED_RPC_REG_CONVERTER_NAME);
273 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
274 metadata.setActivation(ReferenceMetadata.ACTIVATION_LAZY);
275 metadata.setRuntimeClass(RoutedRpcRegistrationConverter.class);
276 registry.registerTypeConverter(metadata);
280 private void registerRpcRegistryServiceRefBean(ParserContext context) {
281 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
282 if(registry.getComponentDefinition(RPC_REGISTRY_NAME) == null) {
283 MutableReferenceMetadata metadata = createServiceRef(context, RpcProviderRegistry.class, null);
284 metadata.setId(RPC_REGISTRY_NAME);
285 registry.registerComponentDefinition(metadata);
289 private Metadata parseNotificationListener(Element element, ParserContext context) {
290 registerNotificationServiceRefBean(context);
292 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
293 metadata.setId(context.generateId());
294 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
295 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
296 metadata.setRuntimeClass(NotificationListenerBean.class);
297 metadata.setInitMethod("init");
298 metadata.setDestroyMethod("destroy");
299 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
300 metadata.addProperty("notificationService", createRef(context, NOTIFICATION_SERVICE_NAME));
301 metadata.addProperty("notificationListener", createRef(context, element.getAttribute(REF_ATTR)));
303 LOG.debug("parseNotificationListener returning {}", metadata);
308 private void registerNotificationServiceRefBean(ParserContext context) {
309 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
310 if(registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) {
311 MutableReferenceMetadata metadata = createServiceRef(context, NotificationService.class, null);
312 metadata.setId(NOTIFICATION_SERVICE_NAME);
313 registry.registerComponentDefinition(metadata);
317 private Metadata parseClusteredAppConfig(Element element, ParserContext context) {
318 LOG.debug("parseClusteredAppConfig");
320 // Find the default-config child element representing the default app config XML, if present.
321 Element defaultConfigElement = null;
322 NodeList children = element.getChildNodes();
323 for(int i = 0; i < children.getLength(); i++) {
324 Node child = children.item(i);
325 if(nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
326 defaultConfigElement = (Element) child;
331 Element defaultAppConfigElement = null;
332 if(defaultConfigElement != null) {
333 // Find the CDATA element containing the default app config XML.
334 children = defaultConfigElement.getChildNodes();
335 for(int i = 0; i < children.getLength(); i++) {
336 Node child = children.item(i);
337 if(child.getNodeType() == Node.CDATA_SECTION_NODE) {
338 defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG, child.getTextContent());
344 return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
345 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
346 DataStoreAppConfigMetadata.LIST_KEY_VALUE), defaultAppConfigElement);
349 private Element parseXML(String name, String xml) {
350 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
351 builderFactory.setNamespaceAware(true);
352 builderFactory.setCoalescing(true);
353 builderFactory.setIgnoringElementContentWhitespace(true);
354 builderFactory.setIgnoringComments(true);
357 return builderFactory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
358 } catch(Exception e) {
359 throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml));
363 private static ValueMetadata createValue(ParserContext context, String value) {
364 MutableValueMetadata m = context.createMetadata(MutableValueMetadata.class);
365 m.setStringValue(value);
369 private static MutableReferenceMetadata createServiceRef(ParserContext context, Class<?> cls, String filter) {
370 MutableReferenceMetadata m = context.createMetadata(MutableReferenceMetadata.class);
371 m.setRuntimeInterface(cls);
372 m.setInterface(cls.getName());
373 m.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
374 m.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
383 private static RefMetadata createRef(ParserContext context, String id) {
384 MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
385 metadata.setComponentId(id);
389 private static String getId(ParserContext context, Element element) {
390 if(element.hasAttribute(ID_ATTR)) {
391 return element.getAttribute(ID_ATTR);
393 return context.generateId();
397 private static boolean nodeNameEquals(Node node, String name) {
398 return name.equals(node.getNodeName()) || name.equals(node.getLocalName());