Merge ".gitignore .factorypath created by m2e-apt"
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / schema / mapping / NetconfMessageTransformer.java
1 /*
2  * Copyright (c) 2014 Cisco 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.netconf.sal.connect.netconf.schema.mapping;
9
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;
14
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;
25 import java.util.Map;
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;
56
57 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
58
59     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
60
61     private static final Function<SchemaNode, QName> QNAME_FUNCTION = new Function<SchemaNode, QName>() {
62         @Override
63         public QName apply(final SchemaNode rpcDefinition) {
64             return rpcDefinition.getQName();
65         }
66     };
67
68     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = new Function<SchemaNode, QName>() {
69         @Override
70         public QName apply(final SchemaNode notification) {
71             return QNAME_FUNCTION.apply(notification).withoutRevision();
72         }
73     };
74
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;
81
82     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
83         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
84     }
85
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;
93     }
94
95     @Override
96     public synchronized DOMNotification toNotification(final NetconfMessage message) {
97         final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
98         final QName notificationNoRev;
99         try {
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);
103         }
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());
107
108         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
109
110         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
111
112         final Element element = stripped.getValue().getDomElement();
113         final ContainerNode content;
114         try {
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);
119         }
120         return new NetconfDeviceNotification(content, stripped.getKey());
121     }
122
123     private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
124         Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
125
126         return Collections.max(notificationDefinitions, cmp);
127     }
128
129     @Override
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;
134
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();
140         }
141
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());
145         }
146
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);
150
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);
154
155         try {
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);
162         }
163
164         final Document node = result.getNode().getOwnerDocument();
165
166         return new NetconfMessage(node);
167     }
168
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());
173     }
174
175
176     @Override
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;
184
185             try {
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);
189             }
190
191             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
192                     .withChild(dataNode).build();
193         } else {
194
195             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
196
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();
202             }
203
204             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
205             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
206
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;
213             } else {
214                 final Element element = message.getDocument().getDocumentElement();
215                 try {
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);
220                 }
221             }
222         }
223         return new DefaultDOMRpcResult(normalizedNode);
224     }
225
226     static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
227         private final ContainerNode content;
228         private final SchemaPath schemaPath;
229         private final Date eventTime;
230
231         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
232             this.content = content;
233             this.eventTime = eventTime;
234             this.schemaPath = toPath(content.getNodeType());
235         }
236
237         @Nonnull
238         @Override
239         public SchemaPath getType() {
240             return schemaPath;
241
242         }
243
244         @Nonnull
245         @Override
246         public ContainerNode getBody() {
247             return content;
248         }
249
250         @Override
251         public Date getEventTime() {
252             return eventTime;
253         }
254     }
255 }