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.Function;
15 import com.google.common.base.Preconditions;
16 import com.google.common.collect.Maps;
17 import com.google.common.collect.Multimap;
18 import com.google.common.collect.Multimaps;
19 import java.io.IOException;
20 import java.util.Collection;
21 import java.util.Collections;
22 import java.util.Comparator;
23 import java.util.Date;
25 import javax.annotation.Nonnull;
26 import javax.xml.stream.XMLStreamException;
27 import javax.xml.transform.dom.DOMResult;
28 import org.opendaylight.controller.config.util.xml.MissingNameSpaceException;
29 import org.opendaylight.controller.config.util.xml.XmlElement;
30 import org.opendaylight.controller.md.sal.dom.api.DOMEvent;
31 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
32 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
33 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
34 import org.opendaylight.netconf.api.NetconfMessage;
35 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
36 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
37 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
38 import org.opendaylight.yangtools.yang.common.QName;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
42 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
43 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
44 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
45 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53 import org.w3c.dom.Document;
54 import org.w3c.dom.Element;
56 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
58 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
60 private static final Function<SchemaNode, QName> QNAME_FUNCTION = rpcDefinition -> rpcDefinition.getQName();
62 private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION =
63 notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
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;
70 private final DomToNormalizedNodeParserFactory parserFactory;
72 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
73 this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
76 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
77 final BaseSchema baseSchema) {
78 this.counter = new MessageCounter();
79 this.schemaContext = schemaContext;
80 parserFactory = DomToNormalizedNodeParserFactory
81 .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
82 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
83 mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
84 this.baseSchema = baseSchema;
88 public synchronized DOMNotification toNotification(final NetconfMessage message) {
89 final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
90 final QName notificationNoRev;
92 notificationNoRev = QName.create(
93 stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
94 } catch (final MissingNameSpaceException e) {
95 throw new IllegalArgumentException(
96 "Unable to parse notification " + message + ", cannot find namespace", e);
98 final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
99 Preconditions.checkArgument(notificationDefinitions.size() > 0,
100 "Unable to parse notification %s, unknown notification. Available notifications: %s",
101 notificationDefinitions, mappedNotifications.keySet());
103 final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
105 final ContainerSchemaNode notificationAsContainerSchemaNode =
106 NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
108 final Element element = stripped.getValue().getDomElement();
109 final ContainerNode content;
111 content = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
112 notificationAsContainerSchemaNode);
113 } catch (IllegalArgumentException e) {
114 throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
116 return new NetconfDeviceNotification(content, stripped.getKey());
119 private static NotificationDefinition getMostRecentNotification(
120 final Collection<NotificationDefinition> notificationDefinitions) {
121 Comparator<NotificationDefinition> cmp = (o1, o2) ->
122 o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
124 return Collections.max(notificationDefinitions, cmp);
128 public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
129 // In case no input for rpc is defined, we can simply construct the payload here
130 final QName rpcQName = rpc.getLastComponent();
131 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
133 // Determine whether a base netconf operation is being invoked
134 // and also check if the device exposed model for base netconf.
135 // If no, use pre built base netconf operations model
136 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
137 if (needToUseBaseCtx) {
138 currentMappedRpcs = baseSchema.getMappedRpcs();
141 Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
142 "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
143 if (currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
144 return new NetconfMessage(NetconfMessageTransformUtil
145 .prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
148 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
149 Preconditions.checkArgument(payload instanceof ContainerNode,
150 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
152 // Set the path to the input of rpc for the node stream writer
153 rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
154 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
157 // If the schema context for netconf device does not contain model for base netconf operations,
158 // use default pre build context with just the base model
159 // This way operations like lock/unlock are supported even if the source for base model was not provided
160 SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
161 NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
162 } catch (final XMLStreamException | IOException | IllegalStateException e) {
163 throw new IllegalStateException("Unable to serialize " + rpc, e);
166 final Document node = result.getNode().getOwnerDocument();
168 return new NetconfMessage(node);
171 private static boolean isBaseOrNotificationRpc(final QName rpc) {
172 return rpc.getNamespace().equals(NETCONF_URI)
173 || rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace())
174 || rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
179 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
180 final NormalizedNode<?, ?> normalizedNode;
181 final QName rpcQName = rpc.getLastComponent();
182 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
183 final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
184 final ContainerSchemaNode schemaForDataRead =
185 NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
186 final ContainerNode dataNode;
190 parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
191 } catch (IllegalArgumentException e) {
192 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
195 normalizedNode = Builders.containerBuilder()
196 .withNodeIdentifier(new YangInstanceIdentifier
197 .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
198 .withChild(dataNode).build();
201 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
203 // Determine whether a base netconf operation is being invoked
204 // and also check if the device exposed model for base netconf.
205 // If no, use pre built base netconf operations model
206 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
207 if (needToUseBaseCtx) {
208 currentMappedRpcs = baseSchema.getMappedRpcs();
211 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
212 Preconditions.checkArgument(rpcDefinition != null,
213 "Unable to parse response of %s, the rpc is unknown", rpcQName);
215 // In case no input for rpc is defined, we can simply construct the payload here
216 if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
217 Preconditions.checkArgument(XmlElement.fromDomDocument(
218 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
219 "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
220 normalizedNode = null;
222 final Element element = message.getDocument().getDocumentElement();
224 normalizedNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
225 rpcDefinition.getOutput());
226 } catch (IllegalArgumentException e) {
227 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
231 return new DefaultDOMRpcResult(normalizedNode);
234 static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
235 private final ContainerNode content;
236 private final SchemaPath schemaPath;
237 private final Date eventTime;
239 NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
240 this.content = content;
241 this.eventTime = eventTime;
242 this.schemaPath = toPath(content.getNodeType());
247 public SchemaPath getType() {
254 public ContainerNode getBody() {
259 public Date getEventTime() {