Mass conversion to static methods
[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.toPath;
13
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;
24 import java.util.Map;
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;
55
56 public class NetconfMessageTransformer implements MessageTransformer<NetconfMessage> {
57
58     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformer.class);
59
60     private static final Function<SchemaNode, QName> QNAME_FUNCTION = rpcDefinition -> rpcDefinition.getQName();
61
62     private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
63
64     private final SchemaContext schemaContext;
65     private final BaseSchema baseSchema;
66     private final MessageCounter counter;
67     private final Map<QName, RpcDefinition> mappedRpcs;
68     private final Multimap<QName, NotificationDefinition> mappedNotifications;
69     private final DomToNormalizedNodeParserFactory parserFactory;
70
71     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing) {
72         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
73     }
74
75     public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
76         this.counter = new MessageCounter();
77         this.schemaContext = schemaContext;
78         parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
79         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
80         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
81         this.baseSchema = baseSchema;
82     }
83
84     @Override
85     public synchronized DOMNotification toNotification(final NetconfMessage message) {
86         final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
87         final QName notificationNoRev;
88         try {
89             notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
90         } catch (final MissingNameSpaceException e) {
91             throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
92         }
93         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
94         Preconditions.checkArgument(notificationDefinitions.size() > 0,
95                 "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
96
97         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
98
99         final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
100
101         final Element element = stripped.getValue().getDomElement();
102         final ContainerNode content;
103         try {
104             content = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
105                 notificationAsContainerSchemaNode);
106         } catch (IllegalArgumentException e) {
107             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
108         }
109         return new NetconfDeviceNotification(content, stripped.getKey());
110     }
111
112     private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
113         Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
114
115         return Collections.max(notificationDefinitions, cmp);
116     }
117
118     @Override
119     public NetconfMessage toRpcRequest(SchemaPath rpc, final NormalizedNode<?, ?> payload) {
120         // In case no input for rpc is defined, we can simply construct the payload here
121         final QName rpcQName = rpc.getLastComponent();
122         Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
123
124         // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
125         // If no, use pre built base netconf operations model
126         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
127         if(needToUseBaseCtx) {
128             currentMappedRpcs = baseSchema.getMappedRpcs();
129         }
130
131         Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
132         if(currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
133             return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
134         }
135
136         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
137         Preconditions.checkArgument(payload instanceof ContainerNode,
138                 "Transforming an rpc with input: %s, payload has to be a container, but was: %s", rpcQName, payload);
139
140         // Set the path to the input of rpc for the node stream writer
141         rpc = rpc.createChild(QName.create(rpcQName, "input").intern());
142         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
143
144         try {
145             // 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
146             // This way operations like lock/unlock are supported even if the source for base model was not provided
147             SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
148             NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
149         } catch (final XMLStreamException | IOException | IllegalStateException e) {
150             throw new IllegalStateException("Unable to serialize " + rpc, e);
151         }
152
153         final Document node = result.getNode().getOwnerDocument();
154
155         return new NetconfMessage(node);
156     }
157
158     private static boolean isBaseOrNotificationRpc(final QName rpc) {
159         return rpc.getNamespace().equals(NETCONF_URI) ||
160                 rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
161                 rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
162     }
163
164
165     @Override
166     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
167         final NormalizedNode<?, ?> normalizedNode;
168         final QName rpcQName = rpc.getLastComponent();
169         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
170             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
171             final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
172             final ContainerNode dataNode;
173
174             try {
175                 dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
176             } catch (IllegalArgumentException e) {
177                 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
178             }
179
180             normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
181                     .withChild(dataNode).build();
182         } else {
183
184             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
185
186             // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
187             // If no, use pre built base netconf operations model
188             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
189             if(needToUseBaseCtx) {
190                 currentMappedRpcs = baseSchema.getMappedRpcs();
191             }
192
193             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
194             Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
195
196             // In case no input for rpc is defined, we can simply construct the payload here
197             if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
198                 Preconditions.checkArgument(XmlElement.fromDomDocument(
199                     message.getDocument()).getOnlyChildElementWithSameNamespaceOptionally("ok").isPresent(),
200                     "Unexpected content in response of rpc: %s, %s", rpcDefinition.getQName(), message);
201                 normalizedNode = null;
202             } else {
203                 final Element element = message.getDocument().getDocumentElement();
204                 try {
205                     normalizedNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(element),
206                         rpcDefinition.getOutput());
207                 } catch (IllegalArgumentException e) {
208                     throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
209                 }
210             }
211         }
212         return new DefaultDOMRpcResult(normalizedNode);
213     }
214
215     static class NetconfDeviceNotification implements DOMNotification, DOMEvent {
216         private final ContainerNode content;
217         private final SchemaPath schemaPath;
218         private final Date eventTime;
219
220         NetconfDeviceNotification(final ContainerNode content, final Date eventTime) {
221             this.content = content;
222             this.eventTime = eventTime;
223             this.schemaPath = toPath(content.getNodeType());
224         }
225
226         @Nonnull
227         @Override
228         public SchemaPath getType() {
229             return schemaPath;
230
231         }
232
233         @Nonnull
234         @Override
235         public ContainerNode getBody() {
236             return content;
237         }
238
239         @Override
240         public Date getEventTime() {
241             return eventTime;
242         }
243     }
244 }