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.stripNotification;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
15 import com.google.common.base.Function;
16 import com.google.common.base.Preconditions;
17 import com.google.common.collect.Maps;
18 import com.google.common.collect.Multimap;
19 import com.google.common.collect.Multimaps;
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.Date;
26 import javax.annotation.Nonnull;
27 import javax.xml.stream.XMLStreamException;
28 import javax.xml.transform.dom.DOMResult;
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.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
44 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
45 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
48 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
49 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
50 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 import org.w3c.dom.Document;
55 import org.w3c.dom.Element;
57 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
59 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
61 private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
63 public QName apply(final SchemaNode rpcDefinition) {
64 return rpcDefinition.getQName();
68 private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
70 public QName apply(final SchemaNode notification) {
71 return QNAME_FUNCTION.apply(notification).withoutRevision();
75 private final SchemaContext schemaContext;
76 private final BaseSchema baseSchema;
77 private final MessageCounter counter;
78 private final Map<QName, RpcDefinition> mappedRpcs;
79 private final Multimap<QName, NotificationDefinition> mappedNotifications;
80 private final DomToNormalizedNodeParserFactory parserFactory;
82 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
83 this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
86 public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
87 this.counter = new MessageCounter();
88 this.schemaContext = schemaContext;
89 parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
90 mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
91 mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
92 this.baseSchema = baseSchema;
96 public synchronized DOMNotification toNotification(final NetconfMessage message) {
97 final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
98 final QName notificationNoRev;
100 notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
101 } catch (final MissingNameSpaceException e) {
102 throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
104 final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
105 Preconditions.checkArgument(notificationDefinitions.size() > 0,
106 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
108 final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
110 final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
112 final Element element = stripped.getValue().getDomElement();
113 final ContainerNode content;
115 content = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
116 notificationAsContainerSchemaNode);
117 } catch (IllegalArgumentException e) {
118 throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
120 return new NetconfDeviceNotification(content, stripped.getKey());
123 private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
124 Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
126 return Collections.max(notificationDefinitions, cmp);
130 public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
131 // In case no input for rpc is defined, we can simply construct the payload here
132 final QName rpcQName = rpc.getLastComponent();
133 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
135 // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
136 // If no, use pre built base netconf operations model
137 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
138 if(needToUseBaseCtx) {
139 currentMappedRpcs = baseSchema.getMappedRpcs();
142 Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
143 if(currentMappedRpcs.get(rpcQName).getInput() == null) {
144 return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
147 Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
148 Preconditions.checkArgument(payload instanceof ContainerNode,
149 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
151 // Set the path to the input of rpc for the node stream writer
152 rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
153 final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
156 // If the schema context for netconf device does not contain model for base netconf operations, use default pre build context with just the base model
157 // This way operations like lock/unlock are supported even if the source for base model was not provided
158 SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
159 NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
160 } catch (final XMLStreamException | IOException | IllegalStateException e) {
161 throw new IllegalStateException("Unable to serialize " + rpc, e);
164 final Document node = result.getNode().getOwnerDocument();
166 return new NetconfMessage(node);
169 private boolean isBaseOrNotificationRpc(final QName rpc) {
170 return rpc.getNamespace().equals(NETCONF_URI) ||
171 rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
172 rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
177 public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
178 final NormalizedNode<?, ?> normalizedNode;
179 final QName rpcQName = rpc.getLastComponent();
180 if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
181 final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
182 final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
183 final ContainerNode dataNode;
186 dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
187 } catch (IllegalArgumentException e) {
188 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
191 normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
192 .withChild(dataNode).build();
195 Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
197 // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
198 // If no, use pre built base netconf operations model
199 final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
200 if(needToUseBaseCtx) {
201 currentMappedRpcs = baseSchema.getMappedRpcs();
204 final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
205 Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
207 // In case no input for rpc is defined, we can simply construct the payload here
208 if (rpcDefinition.getOutput() == null) {
209 Preconditions.checkArgument(XmlElement.fromDomDocument(
210 message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
211 "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
212 normalizedNode = null;
214 final Element element = message.getDocument().getDocumentElement();
216 normalizedNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
217 rpcDefinition.getOutput());
218 } catch (IllegalArgumentException e) {
219 throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
223 return new DefaultDOMRpcResult(normalizedNode);
226 static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
227 private final ContainerNode content;
228 private final SchemaPath schemaPath;
229 private final Date eventTime;
231 NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
232 this.content = content;
233 this.eventTime = eventTime;
234 this.schemaPath = toPath(content.getNodeType());
239 public SchemaPath getType() {
246 public ContainerNode getBody() {
251 public Date getEventTime() {