Fixup checkstyle
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / ext / OpendaylightNamespaceHandler.java
1 /*
2  * Copyright (c) 2016 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.blueprint.ext;
9
10 import com.google.common.base.Strings;
11 import java.io.IOException;
12 import java.io.StringReader;
13 import java.net.URL;
14 import java.util.Set;
15 import org.apache.aries.blueprint.ComponentDefinitionRegistry;
16 import org.apache.aries.blueprint.NamespaceHandler;
17 import org.apache.aries.blueprint.ParserContext;
18 import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
19 import org.apache.aries.blueprint.mutable.MutableRefMetadata;
20 import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
21 import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
22 import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
23 import org.apache.aries.blueprint.mutable.MutableValueMetadata;
24 import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
25 import org.opendaylight.yangtools.util.xml.UntrustedXML;
26 import org.osgi.service.blueprint.container.ComponentDefinitionException;
27 import org.osgi.service.blueprint.reflect.BeanMetadata;
28 import org.osgi.service.blueprint.reflect.ComponentMetadata;
29 import org.osgi.service.blueprint.reflect.Metadata;
30 import org.osgi.service.blueprint.reflect.RefMetadata;
31 import org.osgi.service.blueprint.reflect.ReferenceMetadata;
32 import org.osgi.service.blueprint.reflect.ServiceMetadata;
33 import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
34 import org.osgi.service.blueprint.reflect.ValueMetadata;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.w3c.dom.Attr;
38 import org.w3c.dom.Element;
39 import org.w3c.dom.Node;
40 import org.w3c.dom.NodeList;
41 import org.xml.sax.InputSource;
42 import org.xml.sax.SAXException;
43
44 /**
45  * The NamespaceHandler for Opendaylight blueprint extensions.
46  *
47  * @author Thomas Pantelis
48  */
49 public final class OpendaylightNamespaceHandler implements NamespaceHandler {
50     public static final String NAMESPACE_1_0_0 = "http://opendaylight.org/xmlns/blueprint/v1.0.0";
51
52     private static final Logger LOG = LoggerFactory.getLogger(OpendaylightNamespaceHandler.class);
53     private static final String TYPE_ATTR = "type";
54     private static final String UPDATE_STRATEGY_ATTR = "update-strategy";
55     private static final String COMPONENT_PROCESSOR_NAME = ComponentProcessor.class.getName();
56     private static final String RESTART_DEPENDENTS_ON_UPDATES = "restart-dependents-on-updates";
57     private static final String USE_DEFAULT_FOR_REFERENCE_TYPES = "use-default-for-reference-types";
58     private static final String CLUSTERED_APP_CONFIG = "clustered-app-config";
59     private static final String ID_ATTR = "id";
60
61     @SuppressWarnings("rawtypes")
62     @Override
63     public Set<Class> getManagedClasses() {
64         return Set.of();
65     }
66
67     @Override
68     public URL getSchemaLocation(final String namespace) {
69         if (NAMESPACE_1_0_0.equals(namespace)) {
70             URL url = getClass().getResource("/opendaylight-blueprint-ext-1.0.0.xsd");
71             LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url);
72             return url;
73         }
74
75         return null;
76     }
77
78     @Override
79     public Metadata parse(final Element element, final ParserContext context) {
80         LOG.debug("In parse for {}", element);
81
82         if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
83             return parseClusteredAppConfig(element, context);
84         }
85
86         throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
87     }
88
89     @Override
90     public ComponentMetadata decorate(final Node node, final ComponentMetadata component, final ParserContext context) {
91         if (node instanceof Attr) {
92             if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) {
93                 return decorateRestartDependentsOnUpdates((Attr) node, component, context);
94             } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) {
95                 return decorateUseDefaultForReferenceTypes((Attr) node, component, context);
96             } else if (nodeNameEquals(node, TYPE_ATTR)) {
97                 if (component instanceof ServiceReferenceMetadata) {
98                     return decorateServiceReferenceType((Attr) node, component, context);
99                 } else if (component instanceof ServiceMetadata) {
100                     return decorateServiceType((Attr)node, component, context);
101                 }
102
103                 throw new ComponentDefinitionException("Attribute " + node.getNodeName()
104                         + " can only be used on a <reference>, <reference-list> or <service> element");
105             }
106
107             throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
108         } else {
109             throw new ComponentDefinitionException("Unsupported node type: " + node);
110         }
111     }
112
113     private static ComponentMetadata decorateServiceType(final Attr attr, final ComponentMetadata component,
114             final ParserContext context) {
115         if (!(component instanceof MutableServiceMetadata service)) {
116             throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
117         }
118
119         LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
120
121         service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
122         return component;
123     }
124
125     private static ComponentMetadata decorateServiceReferenceType(final Attr attr, final ComponentMetadata component,
126             final ParserContext context) {
127         if (!(component instanceof MutableServiceReferenceMetadata)) {
128             throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
129         }
130
131         // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
132         // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
133         // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
134         // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
135         // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
136         // but as long as there's at least one processor registered, it correctly uses the extended filter.
137         registerComponentProcessor(context);
138
139         MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
140         String oldFilter = serviceRef.getExtendedFilter() == null ? null :
141             serviceRef.getExtendedFilter().getStringValue();
142
143         String filter;
144         if (Strings.isNullOrEmpty(oldFilter)) {
145             filter = String.format("(type=%s)", attr.getValue());
146         } else {
147             filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
148         }
149
150         LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
151                 serviceRef.getId(), attr.getValue(), oldFilter, filter);
152
153         serviceRef.setExtendedFilter(createValue(context, filter));
154         return component;
155     }
156
157     private static ComponentMetadata decorateRestartDependentsOnUpdates(final Attr attr,
158             final ComponentMetadata component, final ParserContext context) {
159         return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
160     }
161
162     private static ComponentMetadata decorateUseDefaultForReferenceTypes(final Attr attr,
163             final ComponentMetadata component, final ParserContext context) {
164         return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
165     }
166
167     private static ComponentMetadata enableComponentProcessorProperty(final Attr attr,
168             final ComponentMetadata component, final ParserContext context, final String propertyName) {
169         if (component != null) {
170             throw new ComponentDefinitionException("Attribute " + attr.getNodeName()
171                     + " can only be used on the root <blueprint> element");
172         }
173
174         LOG.debug("Property {} = {}", propertyName, attr.getValue());
175
176         if (!Boolean.parseBoolean(attr.getValue())) {
177             return component;
178         }
179
180         MutableBeanMetadata metadata = registerComponentProcessor(context);
181         metadata.addProperty(propertyName, createValue(context, "true"));
182
183         return component;
184     }
185
186     private static MutableBeanMetadata registerComponentProcessor(final ParserContext context) {
187         ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
188         MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
189         if (metadata == null) {
190             metadata = createBeanMetadata(context, COMPONENT_PROCESSOR_NAME, ComponentProcessor.class, false, true);
191             metadata.setProcessor(true);
192             addBlueprintBundleRefProperty(context, metadata);
193             metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
194                     BlueprintContainerRestartService.class, null));
195
196             LOG.debug("Registering ComponentProcessor bean: {}", metadata);
197
198             registry.registerComponentDefinition(metadata);
199         }
200
201         return metadata;
202     }
203
204     private static Metadata parseClusteredAppConfig(final Element element, final ParserContext context) {
205         LOG.debug("parseClusteredAppConfig");
206
207         // Find the default-config child element representing the default app config XML, if present.
208         Element defaultConfigElement = null;
209         NodeList children = element.getChildNodes();
210         for (int i = 0; i < children.getLength(); i++) {
211             Node child = children.item(i);
212             if (nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
213                 defaultConfigElement = (Element) child;
214                 break;
215             }
216         }
217
218         Element defaultAppConfigElement = null;
219         if (defaultConfigElement != null) {
220             // Find the CDATA element containing the default app config XML.
221             children = defaultConfigElement.getChildNodes();
222             for (int i = 0; i < children.getLength(); i++) {
223                 Node child = children.item(i);
224                 if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
225                     defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG,
226                             child.getTextContent());
227                     break;
228                 }
229             }
230         }
231
232         return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
233                 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
234                         DataStoreAppConfigMetadata.LIST_KEY_VALUE), element.getAttribute(
235                         DataStoreAppConfigMetadata.DEFAULT_CONFIG_FILE_NAME), parseUpdateStrategy(
236                         element.getAttribute(UPDATE_STRATEGY_ATTR)), defaultAppConfigElement);
237     }
238
239     private static UpdateStrategy parseUpdateStrategy(final String updateStrategyValue) {
240         if (Strings.isNullOrEmpty(updateStrategyValue)
241                 || updateStrategyValue.equalsIgnoreCase(UpdateStrategy.RELOAD.name())) {
242             return UpdateStrategy.RELOAD;
243         } else if (updateStrategyValue.equalsIgnoreCase(UpdateStrategy.NONE.name())) {
244             return UpdateStrategy.NONE;
245         } else {
246             LOG.warn("update-strategy {} not supported, using reload", updateStrategyValue);
247             return UpdateStrategy.RELOAD;
248         }
249     }
250
251     private static Element parseXML(final String name, final String xml) {
252         try {
253             return UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
254         } catch (SAXException | IOException e) {
255             throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml), e);
256         }
257     }
258
259     private static ValueMetadata createValue(final ParserContext context, final String value) {
260         MutableValueMetadata metadata = context.createMetadata(MutableValueMetadata.class);
261         metadata.setStringValue(value);
262         return metadata;
263     }
264
265     private static MutableReferenceMetadata createServiceRef(final ParserContext context, final Class<?> cls,
266             final String filter) {
267         MutableReferenceMetadata metadata = context.createMetadata(MutableReferenceMetadata.class);
268         metadata.setRuntimeInterface(cls);
269         metadata.setInterface(cls.getName());
270         metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
271         metadata.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
272
273         if (filter != null) {
274             metadata.setFilter(filter);
275         }
276
277         return metadata;
278     }
279
280     private static RefMetadata createRef(final ParserContext context, final String id) {
281         MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
282         metadata.setComponentId(id);
283         return metadata;
284     }
285
286     private static String getId(final ParserContext context, final Element element) {
287         if (element.hasAttribute(ID_ATTR)) {
288             return element.getAttribute(ID_ATTR);
289         } else {
290             return context.generateId();
291         }
292     }
293
294     private static boolean nodeNameEquals(final Node node, final String name) {
295         return name.equals(node.getNodeName()) || name.equals(node.getLocalName());
296     }
297
298     private static void addBlueprintBundleRefProperty(final ParserContext context, final MutableBeanMetadata metadata) {
299         metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
300     }
301
302     private static MutableBeanMetadata createBeanMetadata(final ParserContext context, final String id,
303             final Class<?> runtimeClass, final boolean initMethod, final boolean destroyMethod) {
304         MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
305         metadata.setId(id);
306         metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
307         metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
308         metadata.setRuntimeClass(runtimeClass);
309
310         if (initMethod) {
311             metadata.setInitMethod("init");
312         }
313
314         if (destroyMethod) {
315             metadata.setDestroyMethod("destroy");
316         }
317
318         return metadata;
319     }
320 }