2 * Copyright (c) 2014 Cisco 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.netconf.sal.connect.netconf.schema.mapping;
10 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.IETF_NETCONF_NOTIFICATIONS;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_URI;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
14 import com.google.common.base.Preconditions;
15 import com.google.common.collect.Maps;
16 import com.google.common.collect.Multimap;
17 import com.google.common.collect.Multimaps;
18 import java.io.IOException;
19 import java.net.URISyntaxException;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Date;
24 import javax.annotation.Nonnull;
25 import javax.xml.parsers.ParserConfigurationException;
26 import javax.xml.stream.XMLStreamException;
27 import javax.xml.transform.dom.DOMResult;
28 import javax.xml.transform.dom.DOMSource;
29 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
30 import org.opendaylight.controller.config.util.xml.XmlElement;
31 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
32 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
33 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
34 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
35 import org.opendaylight.netconf.api.NetconfMessage;
36 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
37 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
38 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.common.Revision;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
46 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
48 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
49 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
51 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 import org.w3c.dom.Document;
58 import org.w3c.dom.Element;
59 import org.xml.sax.SAXException;
61 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
63 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
65 private final SchemaContext schemaContext;
66 private final BaseSchema baseSchema;
67 private final MessageCounter counter;
68 private final Map<QName, RpcDefinition> mappedRpcs;
69 private final Multimap<QName, NotificationDefinition> mappedNotifications;
71 private final boolean strictParsing;
73 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
74 this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
77 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
78 final BaseSchema baseSchema) {
79 this.counter = new MessageCounter();
80 this.schemaContext = schemaContext;
81 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), SchemaNode::getQName);
82 mappedNotifications = Multimaps.index(schemaContext.getNotifications(),
83 node -> node.getQName().withoutRevision());
84 this.baseSchema = baseSchema;
85 this.strictParsing = strictParsing;
89 public synchronized DOMNotification toNotification(final NetconfMessage message) {
90 final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
91 final QName notificationNoRev;
93 notificationNoRev = QName.create(
94 stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
95 } catch (final MissingNameSpaceException e) {
96 throw new IllegalArgumentException(
97 "Unable to parse notification " + message + ", cannot find namespace", e);
99 final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
100 Preconditions.checkArgument(notificationDefinitions.size() > 0,
101 "Unable to parse notification %s, unknown notification. Available notifications: %s",
102 notificationDefinitions, mappedNotifications.keySet());
104 final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
106 final ContainerSchemaNode notificationAsContainerSchemaNode =
107 NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
109 final Element element = stripped.getValue().getDomElement();
110 final ContainerNode content;
112 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
113 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
114 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
115 notificationAsContainerSchemaNode, strictParsing);
116 xmlParser.traverse(new DOMSource(element));
117 content = (ContainerNode) resultHolder.getResult();
118 } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
119 | SAXException | UnsupportedOperationException e) {
120 throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
122 return new NetconfDeviceNotification(content, stripped.getKey());
125 private static NotificationDefinition getMostRecentNotification(
126 final Collection<NotificationDefinition> notificationDefinitions) {
127 return Collections.max(notificationDefinitions, (o1, o2) ->
128 Revision.compare(o1.getQName().getRevision(), o2.getQName().getRevision()));
132 public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
133 // In case no input for rpc is defined, we can simply construct the payload here
134 final QName rpcQName = rpc.getLastComponent();
135 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
137 // Determine whether a base netconf operation is being invoked
138 // and also check if the device exposed model for base netconf.
139 // If no, use pre built base netconf operations model
140 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
141 if (needToUseBaseCtx) {
142 currentMappedRpcs = baseSchema.getMappedRpcs();
145 Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
146 "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
147 if (currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
148 return new NetconfMessage(NetconfMessageTransformUtil
149 .prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
152 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
153 Preconditions.checkArgument(payload instanceof ContainerNode,
154 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
156 // Set the path to the input of rpc for the node stream writer
157 rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
158 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
161 // If the schema context for netconf device does not contain model for base netconf operations,
162 // use default pre build context with just the base model
163 // This way operations like lock/unlock are supported even if the source for base model was not provided
164 SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
165 NetconfMessageTransformUtil.writeNormalizedRpc((ContainerNode) payload, result, rpc, ctx);
166 } catch (final XMLStreamException | IOException | IllegalStateException e) {
167 throw new IllegalStateException("Unable to serialize " + rpc, e);
170 final Document node = result.getNode().getOwnerDocument();
172 return new NetconfMessage(node);
175 private static boolean isBaseOrNotificationRpc(final QName rpc) {
176 return rpc.getNamespace().equals(NETCONF_URI)
177 || rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace())
178 || rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
182 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
183 final NormalizedNode<?, ?> normalizedNode;
184 final QName rpcQName = rpc.getLastComponent();
185 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
186 final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
187 final ContainerSchemaNode schemaForDataRead =
188 NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
189 final ContainerNode dataNode;
192 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
193 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
194 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext, schemaForDataRead,
196 xmlParser.traverse(new DOMSource(xmlData));
197 dataNode = (ContainerNode) resultHolder.getResult();
198 } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
200 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
203 normalizedNode = Builders.containerBuilder()
204 .withNodeIdentifier(new YangInstanceIdentifier
205 .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
206 .withChild(dataNode).build();
209 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
211 // Determine whether a base netconf operation is being invoked
212 // and also check if the device exposed model for base netconf.
213 // If no, use pre built base netconf operations model
214 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
215 if (needToUseBaseCtx) {
216 currentMappedRpcs = baseSchema.getMappedRpcs();
219 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
220 Preconditions.checkArgument(rpcDefinition != null,
221 "Unable to parse response of %s, the rpc is unknown", rpcQName);
223 // In case no input for rpc is defined, we can simply construct the payload here
224 if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
225 Preconditions.checkArgument(XmlElement.fromDomDocument(
226 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
227 "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
228 normalizedNode = null;
230 final Element element = message.getDocument().getDocumentElement();
232 final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
233 final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
234 final XmlParserStream xmlParser = XmlParserStream.create(writer, schemaContext,
235 rpcDefinition.getOutput(), strictParsing);
236 xmlParser.traverse(new DOMSource(element));
237 normalizedNode = resultHolder.getResult();
238 } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
240 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
244 return new DefaultDOMRpcResult(normalizedNode);
247 static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
248 private final ContainerNode content;
249 private final SchemaPath schemaPath;
250 private final Date eventTime;
252 NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
253 this.content = content;
254 this.eventTime = eventTime;
255 this.schemaPath = toPath(content.getNodeType());
260 public SchemaPath getType() {
267 public ContainerNode getBody() {
272 public Date getEventTime() {