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 final 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(final 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(final Element element, final 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(final Node node, final ComponentMetadata component, final 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 static ComponentMetadata decorateServiceType(final Attr attr, final ComponentMetadata component,
139 final ParserContext context) {
140 if (!(component instanceof MutableServiceMetadata)) {
141 throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
144 MutableServiceMetadata service = (MutableServiceMetadata)component;
146 LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
148 service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
152 private static ComponentMetadata decorateServiceReferenceType(final Attr attr, final ComponentMetadata component,
153 final ParserContext context) {
154 if (!(component instanceof MutableServiceReferenceMetadata)) {
155 throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
158 // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
159 // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
160 // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
161 // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
162 // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
163 // but as long as there's at least one processor registered, it correctly uses the extended filter.
164 registerComponentProcessor(context);
166 MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
167 String oldFilter = serviceRef.getExtendedFilter() == null ? null :
168 serviceRef.getExtendedFilter().getStringValue();
171 if (Strings.isNullOrEmpty(oldFilter)) {
172 filter = String.format("(type=%s)", attr.getValue());
174 filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
177 LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
178 serviceRef.getId(), attr.getValue(), oldFilter, filter);
180 serviceRef.setExtendedFilter(createValue(context, filter));
184 private static ComponentMetadata decorateRestartDependentsOnUpdates(final Attr attr,
185 final ComponentMetadata component, final ParserContext context) {
186 return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
189 private static ComponentMetadata decorateUseDefaultForReferenceTypes(final Attr attr,
190 final ComponentMetadata component, final ParserContext context) {
191 return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
194 private static ComponentMetadata enableComponentProcessorProperty(final Attr attr,
195 final ComponentMetadata component, final ParserContext context, final String propertyName) {
196 if (component != null) {
197 throw new ComponentDefinitionException("Attribute " + attr.getNodeName()
198 + " can only be used on the root <blueprint> element");
201 LOG.debug("{}: {}", propertyName, attr.getValue());
203 if (!Boolean.parseBoolean(attr.getValue())) {
207 MutableBeanMetadata metadata = registerComponentProcessor(context);
208 metadata.addProperty(propertyName, createValue(context, "true"));
213 private static MutableBeanMetadata registerComponentProcessor(final ParserContext context) {
214 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
215 MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
216 if (metadata == null) {
217 metadata = context.createMetadata(MutableBeanMetadata.class);
218 metadata.setProcessor(true);
219 metadata.setId(COMPONENT_PROCESSOR_NAME);
220 metadata.setActivation(BeanMetadata.ACTIVATION_EAGER);
221 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
222 metadata.setRuntimeClass(ComponentProcessor.class);
223 metadata.setDestroyMethod("destroy");
224 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
225 metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
226 BlueprintContainerRestartService.class, null));
228 LOG.debug("Registering ComponentProcessor bean: {}", metadata);
230 registry.registerComponentDefinition(metadata);
236 private static Metadata parseRpcImplementation(final Element element, final ParserContext context) {
237 registerRpcRegistryServiceRefBean(context);
239 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
240 metadata.setId(context.generateId());
241 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
242 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
243 metadata.setRuntimeClass(RpcImplementationBean.class);
244 metadata.setInitMethod("init");
245 metadata.setDestroyMethod("destroy");
246 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
247 metadata.addProperty("rpcRegistry", createRef(context, RPC_REGISTRY_NAME));
248 metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
250 if (element.hasAttribute(INTERFACE)) {
251 metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
254 LOG.debug("parseAddRpcImplementation returning {}", metadata);
259 private static Metadata parseRoutedRpcImplementation(final Element element, final ParserContext context) {
260 registerRpcRegistryServiceRefBean(context);
261 registerRoutedRpcRegistrationConverter(context);
263 ComponentFactoryMetadata metadata = new RoutedRpcMetadata(getId(context, element),
264 element.getAttribute(INTERFACE), element.getAttribute(REF_ATTR));
266 LOG.debug("parseRoutedRpcImplementation returning {}", metadata);
271 private static Metadata parseRpcService(final Element element, final ParserContext context) {
272 ComponentFactoryMetadata metadata = new RpcServiceMetadata(getId(context, element),
273 element.getAttribute(INTERFACE));
275 LOG.debug("parseRpcService returning {}", metadata);
280 private static void registerRoutedRpcRegistrationConverter(final ParserContext context) {
281 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
282 if (registry.getComponentDefinition(ROUTED_RPC_REG_CONVERTER_NAME) == null) {
283 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
284 metadata.setId(ROUTED_RPC_REG_CONVERTER_NAME);
285 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
286 metadata.setActivation(ReferenceMetadata.ACTIVATION_LAZY);
287 metadata.setRuntimeClass(RoutedRpcRegistrationConverter.class);
288 registry.registerTypeConverter(metadata);
292 private static void registerRpcRegistryServiceRefBean(final ParserContext context) {
293 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
294 if (registry.getComponentDefinition(RPC_REGISTRY_NAME) == null) {
295 MutableReferenceMetadata metadata = createServiceRef(context, RpcProviderRegistry.class, null);
296 metadata.setId(RPC_REGISTRY_NAME);
297 registry.registerComponentDefinition(metadata);
301 private static Metadata parseNotificationListener(final Element element, final ParserContext context) {
302 registerNotificationServiceRefBean(context);
304 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
305 metadata.setId(context.generateId());
306 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
307 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
308 metadata.setRuntimeClass(NotificationListenerBean.class);
309 metadata.setInitMethod("init");
310 metadata.setDestroyMethod("destroy");
311 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
312 metadata.addProperty("notificationService", createRef(context, NOTIFICATION_SERVICE_NAME));
313 metadata.addProperty("notificationListener", createRef(context, element.getAttribute(REF_ATTR)));
315 LOG.debug("parseNotificationListener returning {}", metadata);
320 private static void registerNotificationServiceRefBean(final ParserContext context) {
321 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
322 if (registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) {
323 MutableReferenceMetadata metadata = createServiceRef(context, NotificationService.class, null);
324 metadata.setId(NOTIFICATION_SERVICE_NAME);
325 registry.registerComponentDefinition(metadata);
329 private static Metadata parseClusteredAppConfig(final Element element, final ParserContext context) {
330 LOG.debug("parseClusteredAppConfig");
332 // Find the default-config child element representing the default app config XML, if present.
333 Element defaultConfigElement = null;
334 NodeList children = element.getChildNodes();
335 for (int i = 0; i < children.getLength(); i++) {
336 Node child = children.item(i);
337 if (nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
338 defaultConfigElement = (Element) child;
343 Element defaultAppConfigElement = null;
344 if (defaultConfigElement != null) {
345 // Find the CDATA element containing the default app config XML.
346 children = defaultConfigElement.getChildNodes();
347 for (int i = 0; i < children.getLength(); i++) {
348 Node child = children.item(i);
349 if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
350 defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG,
351 child.getTextContent());
357 return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
358 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
359 DataStoreAppConfigMetadata.LIST_KEY_VALUE), element.getAttribute(
360 DataStoreAppConfigMetadata.DEFAULT_CONFIG_FILE_NAME), parseUpdateStrategy(
361 element.getAttribute(UPDATE_STRATEGY_ATTR)), defaultAppConfigElement);
364 private static UpdateStrategy parseUpdateStrategy(final String updateStrategyValue) {
365 if (Strings.isNullOrEmpty(updateStrategyValue)
366 || updateStrategyValue.equalsIgnoreCase(UpdateStrategy.RELOAD.name())) {
367 return UpdateStrategy.RELOAD;
368 } else if (updateStrategyValue.equalsIgnoreCase(UpdateStrategy.NONE.name())) {
369 return UpdateStrategy.NONE;
371 LOG.warn("update-strategy {} not supported, using reload", updateStrategyValue);
372 return UpdateStrategy.RELOAD;
376 private static Metadata parseSpecificReferenceList(final Element element, final ParserContext context) {
377 ComponentFactoryMetadata metadata = new SpecificReferenceListMetadata(getId(context, element),
378 element.getAttribute(INTERFACE));
380 LOG.debug("parseSpecificReferenceList returning {}", metadata);
385 private static Metadata parseStaticReference(final Element element, final ParserContext context) {
386 ComponentFactoryMetadata metadata = new StaticReferenceMetadata(getId(context, element),
387 element.getAttribute(INTERFACE));
389 LOG.debug("parseStaticReference returning {}", metadata);
394 private static Element parseXML(final String name, final String xml) {
395 DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
396 builderFactory.setNamespaceAware(true);
397 builderFactory.setCoalescing(true);
398 builderFactory.setIgnoringElementContentWhitespace(true);
399 builderFactory.setIgnoringComments(true);
402 return builderFactory.newDocumentBuilder().parse(new InputSource(
403 new StringReader(xml))).getDocumentElement();
404 } catch (SAXException | IOException | ParserConfigurationException e) {
405 throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml), e);
409 private static ValueMetadata createValue(final ParserContext context, final String value) {
410 MutableValueMetadata metadata = context.createMetadata(MutableValueMetadata.class);
411 metadata.setStringValue(value);
415 private static MutableReferenceMetadata createServiceRef(final ParserContext context, final Class<?> cls,
416 final String filter) {
417 MutableReferenceMetadata metadata = context.createMetadata(MutableReferenceMetadata.class);
418 metadata.setRuntimeInterface(cls);
419 metadata.setInterface(cls.getName());
420 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
421 metadata.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
423 if (filter != null) {
424 metadata.setFilter(filter);
430 private static RefMetadata createRef(final ParserContext context, final String id) {
431 MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
432 metadata.setComponentId(id);
436 private static String getId(final ParserContext context, final Element element) {
437 if (element.hasAttribute(ID_ATTR)) {
438 return element.getAttribute(ID_ATTR);
440 return context.generateId();
444 private static boolean nodeNameEquals(final Node node, final String name) {
445 return name.equals(node.getNodeName()) || name.equals(node.getLocalName());