Bug 8153: Enforce check-style rules for netconf - sal-netconf-connector
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / util / NetconfMessageTransformUtil.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.util;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableMap;
14 import java.io.IOException;
15 import java.net.URI;
16 import java.time.format.DateTimeParseException;
17 import java.util.AbstractMap;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.Date;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import javax.xml.stream.XMLStreamException;
25 import javax.xml.stream.XMLStreamWriter;
26 import javax.xml.transform.dom.DOMResult;
27 import javax.xml.transform.dom.DOMSource;
28 import org.opendaylight.controller.config.util.xml.DocumentedException;
29 import org.opendaylight.controller.config.util.xml.XmlElement;
30 import org.opendaylight.controller.config.util.xml.XmlUtil;
31 import org.opendaylight.netconf.api.NetconfDocumentedException;
32 import org.opendaylight.netconf.api.NetconfMessage;
33 import org.opendaylight.netconf.notifications.NetconfNotification;
34 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
35 import org.opendaylight.netconf.util.NetconfUtil;
36 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
37 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
38 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
39 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
40 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.common.RpcError;
43 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
44 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
45 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
52 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
53 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
54 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
55 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
56 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
57 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
58 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
59 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65 import org.w3c.dom.Document;
66 import org.w3c.dom.Element;
67
68 public class NetconfMessageTransformUtil {
69
70     private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
71
72     public static final String MESSAGE_ID_PREFIX = "m";
73     public static final String MESSAGE_ID_ATTR = "message-id";
74
75     public static final QName CREATE_SUBSCRIPTION_RPC_QNAME =
76             QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
77     private static final String SUBTREE = "subtree";
78
79     // Blank document used for creation of new DOM nodes
80     private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
81     public static final String EVENT_TIME = "eventTime";
82
83     private NetconfMessageTransformUtil() {}
84
85     public static final QName IETF_NETCONF_MONITORING =
86             QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
87     public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
88     public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
89     public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
90             QName.create(IETF_NETCONF_MONITORING, "format").intern();
91     public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
92             QName.create(IETF_NETCONF_MONITORING, "location").intern();
93     public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
94             QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
95     public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
96             QName.create(IETF_NETCONF_MONITORING, "version").intern();
97     public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
98             QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
99
100     public static final QName IETF_NETCONF_NOTIFICATIONS =
101             QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
102
103     public static final QName NETCONF_QNAME =
104             QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
105     public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
106
107     public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
108     public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
109     public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
110     public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option").intern();
111     public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
112     public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
113     public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
114     public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
115     public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
116     public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
117     public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
118     public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
119     public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
120     public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
121             QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
122     public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
123     public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
124     public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
125     public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
126     public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
127     public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
128     public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
129
130     public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
131             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
132     public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
133
134     public static final URI NETCONF_CANDIDATE_URI = URI
135             .create("urn:ietf:params:netconf:capability:candidate:1.0");
136
137     public static final URI NETCONF_NOTIFICATONS_URI = URI
138             .create("urn:ietf:params:netconf:capability:notification:1.0");
139
140     public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
141             .create("urn:ietf:params:netconf:capability:writable-running:1.0");
142
143     public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
144     public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
145
146     // Discard changes message
147     public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
148             Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
149
150     // Commit changes message
151     public static final ContainerNode COMMIT_RPC_CONTENT =
152             Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
153
154     // Get message
155     public static final ContainerNode GET_RPC_CONTENT =
156             Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(NETCONF_GET_QNAME)).build();
157
158     // Create-subscription changes message
159     public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
160             Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
161
162     public static final DataContainerChild<?, ?> EMPTY_FILTER;
163
164     static {
165         final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
166                 Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
167         anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
168
169         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
170                 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
171         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
172                 NETCONF_TYPE_QNAME.getLocalName(), "subtree");
173
174         anyXmlBuilder.withValue(new DOMSource(element));
175
176         EMPTY_FILTER = anyXmlBuilder.build();
177     }
178
179     public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
180                                                              final SchemaContext ctx) {
181         final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
182                 Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
183         anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
184
185         final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
186
187         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
188                 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
189         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
190                 "subtree");
191
192         try {
193             NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
194         } catch (IOException | XMLStreamException e) {
195             throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
196         }
197         anyXmlBuilder.withValue(new DOMSource(element));
198
199         return anyXmlBuilder.build();
200     }
201
202     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
203             throws NetconfDocumentedException {
204         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
205         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
206
207         if (inputMsgId.equals(outputMsgId) == false) {
208             final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
209                     .put("actual-message-id", outputMsgId)
210                     .put("expected-message-id", inputMsgId)
211                     .build();
212
213             throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
214                     null, NetconfDocumentedException.ErrorType.PROTOCOL,
215                     NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
216                     NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
217         }
218     }
219
220     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
221         if (NetconfMessageUtil.isErrorMessage(output)) {
222             throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
223         }
224     }
225
226     public static RpcError toRpcError(final NetconfDocumentedException ex) {
227         final StringBuilder infoBuilder = new StringBuilder();
228         final Map<String, String> errorInfo = ex.getErrorInfo();
229         if (errorInfo != null) {
230             for (final Entry<String, String> e : errorInfo.entrySet()) {
231                 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
232                         .append("</").append(e.getKey()).append('>');
233
234             }
235         }
236
237         final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
238         return severity == ErrorSeverity.ERROR
239                 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
240                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
241                 : RpcResultBuilder.newWarning(
242                         toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
243                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
244     }
245
246     private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
247         switch (severity) {
248             case WARNING:
249                 return RpcError.ErrorSeverity.WARNING;
250             default:
251                 return RpcError.ErrorSeverity.ERROR;
252         }
253     }
254
255     private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
256         switch (type) {
257             case PROTOCOL:
258                 return RpcError.ErrorType.PROTOCOL;
259             case RPC:
260                 return RpcError.ErrorType.RPC;
261             case TRANSPORT:
262                 return RpcError.ErrorType.TRANSPORT;
263             default:
264                 return RpcError.ErrorType.APPLICATION;
265         }
266     }
267
268     public static NodeIdentifier toId(final PathArgument qname) {
269         return toId(qname.getNodeType());
270     }
271
272     public static NodeIdentifier toId(final QName nodeType) {
273         return new NodeIdentifier(nodeType);
274     }
275
276     public static Element getDataSubtree(final Document doc) {
277         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
278     }
279
280     public static boolean isDataRetrievalOperation(final QName rpc) {
281         return NETCONF_URI.equals(rpc.getNamespace())
282                 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
283                 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
284     }
285
286     public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
287         return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
288     }
289
290     public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
291         return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
292     }
293
294     public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
295         return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
296     }
297
298     public static AnyXmlNode createEditConfigAnyxml(
299             final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
300             final Optional<NormalizedNode<?, ?>> lastChildOverride) {
301         final NormalizedNode<?, ?> configContent;
302
303         if (dataPath.isEmpty()) {
304             Preconditions.checkArgument(lastChildOverride.isPresent(),
305                     "Data has to be present when creating structure for top level element");
306             Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
307                     "Data has to be either container or a list node when creating structure for top level element, "
308                             + "but was: %s", lastChildOverride.get());
309             configContent = lastChildOverride.get();
310         } else {
311             final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
312                     ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
313             configContent = ImmutableNodes
314                     .fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
315         }
316
317         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
318                 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
319         try {
320             NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
321         } catch (IOException | XMLStreamException e) {
322             throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
323         }
324         final DOMSource value = new DOMSource(element);
325
326         return Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build();
327     }
328
329     public static DataContainerChild<?, ?> createEditConfigStructure(
330             final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
331             final Optional<NormalizedNode<?, ?>> lastChildOverride) {
332         return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME))
333                 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
334     }
335
336     public static SchemaPath toPath(final QName rpc) {
337         return SchemaPath.create(true, rpc);
338     }
339
340     public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
341         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
342         final List<XmlElement> childElements = xmlElement.getChildElements();
343         Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
344                 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
345
346         final XmlElement eventTimeElement;
347         final XmlElement notificationElement;
348
349         if (childElements.get(0).getName().equals(EVENT_TIME)) {
350             eventTimeElement = childElements.get(0);
351             notificationElement = childElements.get(1);
352         } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
353             eventTimeElement = childElements.get(1);
354             notificationElement = childElements.get(0);
355         } else {
356             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
357         }
358
359         try {
360             return new AbstractMap.SimpleEntry<>(
361                     NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()),
362                     notificationElement);
363         } catch (final DocumentedException e) {
364             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
365         } catch (final DateTimeParseException e) {
366             LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
367                     NetconfNotification.UNKNOWN_EVENT_TIME, e);
368             return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
369         }
370     }
371
372     public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
373         final Document document = XmlUtil.newDocument();
374         final Element rpcNS =
375                 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
376         // set msg id
377         rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
378         final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
379         rpcNS.appendChild(elementNS);
380         document.appendChild(rpcNS);
381         return new DOMResult(elementNS);
382     }
383
384     @SuppressWarnings("checkstyle:IllegalCatch")
385     public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
386                                           final SchemaPath schemaPath,
387                                           final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
388         final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
389         try {
390             try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
391                     XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
392                 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
393                         new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
394                     final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
395                     normalizedNodeWriter.write(value);
396                     normalizedNodeWriter.flush();
397                 }
398             }
399         } finally {
400             try {
401                 writer.close();
402             } catch (final Exception e) {
403                 LOG.warn("Unable to close resource properly", e);
404             }
405         }
406     }
407 }