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 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.mutable.MutableBeanMetadata;
20 import org.apache.aries.blueprint.mutable.MutableRefMetadata;
21 import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
22 import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
23 import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
24 import org.apache.aries.blueprint.mutable.MutableValueMetadata;
25 import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
26 import org.opendaylight.yangtools.util.xml.UntrustedXML;
27 import org.osgi.service.blueprint.container.ComponentDefinitionException;
28 import org.osgi.service.blueprint.reflect.BeanMetadata;
29 import org.osgi.service.blueprint.reflect.ComponentMetadata;
30 import org.osgi.service.blueprint.reflect.Metadata;
31 import org.osgi.service.blueprint.reflect.RefMetadata;
32 import org.osgi.service.blueprint.reflect.ReferenceMetadata;
33 import org.osgi.service.blueprint.reflect.ServiceMetadata;
34 import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
35 import org.osgi.service.blueprint.reflect.ValueMetadata;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Attr;
39 import org.w3c.dom.Element;
40 import org.w3c.dom.Node;
41 import org.w3c.dom.NodeList;
42 import org.xml.sax.InputSource;
43 import org.xml.sax.SAXException;
46 * The NamespaceHandler for Opendaylight blueprint extensions.
48 * @author Thomas Pantelis
50 public final class OpendaylightNamespaceHandler implements NamespaceHandler {
51 public static final String NAMESPACE_1_0_0 = "http://opendaylight.org/xmlns/blueprint/v1.0.0";
52 static final String ROUTED_RPC_REG_CONVERTER_NAME = "org.opendaylight.blueprint.RoutedRpcRegConverter";
53 static final String DOM_RPC_PROVIDER_SERVICE_NAME = "org.opendaylight.blueprint.DOMRpcProviderService";
54 static final String RPC_REGISTRY_NAME = "org.opendaylight.blueprint.RpcRegistry";
55 static final String BINDING_RPC_PROVIDER_SERVICE_NAME = "org.opendaylight.blueprint.RpcProviderService";
56 static final String SCHEMA_SERVICE_NAME = "org.opendaylight.blueprint.SchemaService";
57 static final String NOTIFICATION_SERVICE_NAME = "org.opendaylight.blueprint.NotificationService";
58 static final String TYPE_ATTR = "type";
59 static final String UPDATE_STRATEGY_ATTR = "update-strategy";
61 private static final Logger LOG = LoggerFactory.getLogger(OpendaylightNamespaceHandler.class);
62 private static final String COMPONENT_PROCESSOR_NAME = ComponentProcessor.class.getName();
63 private static final String RESTART_DEPENDENTS_ON_UPDATES = "restart-dependents-on-updates";
64 private static final String USE_DEFAULT_FOR_REFERENCE_TYPES = "use-default-for-reference-types";
65 private static final String CLUSTERED_APP_CONFIG = "clustered-app-config";
66 private static final String INTERFACE = "interface";
67 private static final String ID_ATTR = "id";
69 @SuppressWarnings("rawtypes")
71 public Set<Class> getManagedClasses() {
72 return Collections.emptySet();
76 public URL getSchemaLocation(final String namespace) {
77 if (NAMESPACE_1_0_0.equals(namespace)) {
78 URL url = getClass().getResource("/opendaylight-blueprint-ext-1.0.0.xsd");
79 LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url);
87 public Metadata parse(final Element element, final ParserContext context) {
88 LOG.debug("In parse for {}", element);
90 if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
91 return parseClusteredAppConfig(element, context);
94 throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
98 public ComponentMetadata decorate(final Node node, final ComponentMetadata component, final ParserContext context) {
99 if (node instanceof Attr) {
100 if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) {
101 return decorateRestartDependentsOnUpdates((Attr) node, component, context);
102 } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) {
103 return decorateUseDefaultForReferenceTypes((Attr) node, component, context);
104 } else if (nodeNameEquals(node, TYPE_ATTR)) {
105 if (component instanceof ServiceReferenceMetadata) {
106 return decorateServiceReferenceType((Attr) node, component, context);
107 } else if (component instanceof ServiceMetadata) {
108 return decorateServiceType((Attr)node, component, context);
111 throw new ComponentDefinitionException("Attribute " + node.getNodeName()
112 + " can only be used on a <reference>, <reference-list> or <service> element");
115 throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
117 throw new ComponentDefinitionException("Unsupported node type: " + node);
121 private static ComponentMetadata decorateServiceType(final Attr attr, final ComponentMetadata component,
122 final ParserContext context) {
123 if (!(component instanceof MutableServiceMetadata service)) {
124 throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
127 LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
129 service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
133 private static ComponentMetadata decorateServiceReferenceType(final Attr attr, final ComponentMetadata component,
134 final ParserContext context) {
135 if (!(component instanceof MutableServiceReferenceMetadata)) {
136 throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
139 // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
140 // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
141 // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
142 // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
143 // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
144 // but as long as there's at least one processor registered, it correctly uses the extended filter.
145 registerComponentProcessor(context);
147 MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
148 String oldFilter = serviceRef.getExtendedFilter() == null ? null :
149 serviceRef.getExtendedFilter().getStringValue();
152 if (Strings.isNullOrEmpty(oldFilter)) {
153 filter = String.format("(type=%s)", attr.getValue());
155 filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
158 LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
159 serviceRef.getId(), attr.getValue(), oldFilter, filter);
161 serviceRef.setExtendedFilter(createValue(context, filter));
165 private static ComponentMetadata decorateRestartDependentsOnUpdates(final Attr attr,
166 final ComponentMetadata component, final ParserContext context) {
167 return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
170 private static ComponentMetadata decorateUseDefaultForReferenceTypes(final Attr attr,
171 final ComponentMetadata component, final ParserContext context) {
172 return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
175 private static ComponentMetadata enableComponentProcessorProperty(final Attr attr,
176 final ComponentMetadata component, final ParserContext context, final String propertyName) {
177 if (component != null) {
178 throw new ComponentDefinitionException("Attribute " + attr.getNodeName()
179 + " can only be used on the root <blueprint> element");
182 LOG.debug("Property {} = {}", propertyName, attr.getValue());
184 if (!Boolean.parseBoolean(attr.getValue())) {
188 MutableBeanMetadata metadata = registerComponentProcessor(context);
189 metadata.addProperty(propertyName, createValue(context, "true"));
194 private static MutableBeanMetadata registerComponentProcessor(final ParserContext context) {
195 ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
196 MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
197 if (metadata == null) {
198 metadata = createBeanMetadata(context, COMPONENT_PROCESSOR_NAME, ComponentProcessor.class, false, true);
199 metadata.setProcessor(true);
200 addBlueprintBundleRefProperty(context, metadata);
201 metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
202 BlueprintContainerRestartService.class, null));
204 LOG.debug("Registering ComponentProcessor bean: {}", metadata);
206 registry.registerComponentDefinition(metadata);
212 private static Metadata parseClusteredAppConfig(final Element element, final ParserContext context) {
213 LOG.debug("parseClusteredAppConfig");
215 // Find the default-config child element representing the default app config XML, if present.
216 Element defaultConfigElement = null;
217 NodeList children = element.getChildNodes();
218 for (int i = 0; i < children.getLength(); i++) {
219 Node child = children.item(i);
220 if (nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
221 defaultConfigElement = (Element) child;
226 Element defaultAppConfigElement = null;
227 if (defaultConfigElement != null) {
228 // Find the CDATA element containing the default app config XML.
229 children = defaultConfigElement.getChildNodes();
230 for (int i = 0; i < children.getLength(); i++) {
231 Node child = children.item(i);
232 if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
233 defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG,
234 child.getTextContent());
240 return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
241 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
242 DataStoreAppConfigMetadata.LIST_KEY_VALUE), element.getAttribute(
243 DataStoreAppConfigMetadata.DEFAULT_CONFIG_FILE_NAME), parseUpdateStrategy(
244 element.getAttribute(UPDATE_STRATEGY_ATTR)), defaultAppConfigElement);
247 private static UpdateStrategy parseUpdateStrategy(final String updateStrategyValue) {
248 if (Strings.isNullOrEmpty(updateStrategyValue)
249 || updateStrategyValue.equalsIgnoreCase(UpdateStrategy.RELOAD.name())) {
250 return UpdateStrategy.RELOAD;
251 } else if (updateStrategyValue.equalsIgnoreCase(UpdateStrategy.NONE.name())) {
252 return UpdateStrategy.NONE;
254 LOG.warn("update-strategy {} not supported, using reload", updateStrategyValue);
255 return UpdateStrategy.RELOAD;
259 private static Element parseXML(final String name, final String xml) {
261 return UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
262 } catch (SAXException | IOException e) {
263 throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml), e);
267 private static ValueMetadata createValue(final ParserContext context, final String value) {
268 MutableValueMetadata metadata = context.createMetadata(MutableValueMetadata.class);
269 metadata.setStringValue(value);
273 private static MutableReferenceMetadata createServiceRef(final ParserContext context, final Class<?> cls,
274 final String filter) {
275 MutableReferenceMetadata metadata = context.createMetadata(MutableReferenceMetadata.class);
276 metadata.setRuntimeInterface(cls);
277 metadata.setInterface(cls.getName());
278 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
279 metadata.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
281 if (filter != null) {
282 metadata.setFilter(filter);
288 private static RefMetadata createRef(final ParserContext context, final String id) {
289 MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
290 metadata.setComponentId(id);
294 private static String getId(final ParserContext context, final Element element) {
295 if (element.hasAttribute(ID_ATTR)) {
296 return element.getAttribute(ID_ATTR);
298 return context.generateId();
302 private static boolean nodeNameEquals(final Node node, final String name) {
303 return name.equals(node.getNodeName()) || name.equals(node.getLocalName());
306 private static void addBlueprintBundleRefProperty(final ParserContext context, final MutableBeanMetadata metadata) {
307 metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
310 private static MutableBeanMetadata createBeanMetadata(final ParserContext context, final String id,
311 final Class<?> runtimeClass, final boolean initMethod, final boolean destroyMethod) {
312 MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
314 metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
315 metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
316 metadata.setRuntimeClass(runtimeClass);
319 metadata.setInitMethod("init");
323 metadata.setDestroyMethod("destroy");