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.util;
10 import static org.opendaylight.netconf.util.NetconfUtil.NETCONF_DATA_QNAME;
11 import static org.opendaylight.netconf.util.NetconfUtil.NETCONF_QNAME;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ImmutableList;
15 import com.google.common.collect.ImmutableMap;
16 import java.io.IOException;
18 import java.time.Instant;
19 import java.time.format.DateTimeParseException;
20 import java.util.AbstractMap.SimpleEntry;
21 import java.util.ArrayDeque;
22 import java.util.Collection;
23 import java.util.Deque;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Locale;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30 import javax.xml.stream.XMLStreamException;
31 import javax.xml.stream.XMLStreamWriter;
32 import javax.xml.transform.dom.DOMResult;
33 import javax.xml.transform.dom.DOMSource;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
36 import org.opendaylight.netconf.api.DocumentedException;
37 import org.opendaylight.netconf.api.FailedNetconfMessage;
38 import org.opendaylight.netconf.api.ModifyAction;
39 import org.opendaylight.netconf.api.NetconfDocumentedException;
40 import org.opendaylight.netconf.api.NetconfMessage;
41 import org.opendaylight.netconf.api.xml.XmlElement;
42 import org.opendaylight.netconf.api.xml.XmlUtil;
43 import org.opendaylight.netconf.notifications.NetconfNotification;
44 import org.opendaylight.netconf.sal.connect.util.MessageCounter;
45 import org.opendaylight.netconf.util.NetconfUtil;
46 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
47 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
51 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
52 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
53 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
54 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
55 import org.opendaylight.yangtools.yang.common.ErrorTag;
56 import org.opendaylight.yangtools.yang.common.ErrorType;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.RpcError;
59 import org.opendaylight.yangtools.yang.common.RpcResult;
60 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
61 import org.opendaylight.yangtools.yang.common.XMLNamespace;
62 import org.opendaylight.yangtools.yang.common.YangConstants;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
72 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
74 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
75 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
76 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
77 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
78 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
79 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
80 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
81 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
82 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
85 import org.w3c.dom.Document;
86 import org.w3c.dom.Element;
88 public final class NetconfMessageTransformUtil {
90 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
92 public static final String MESSAGE_ID_PREFIX = "m";
93 public static final String MESSAGE_ID_ATTR = "message-id";
95 public static final @NonNull QName CREATE_SUBSCRIPTION_RPC_QNAME =
96 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
97 private static final String SUBTREE = "subtree";
99 // Blank document used for creation of new DOM nodes
100 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
101 public static final String EVENT_TIME = "eventTime";
103 private NetconfMessageTransformUtil() {
107 public static final @NonNull QName IETF_NETCONF_MONITORING =
108 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
109 public static final @NonNull QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
110 public static final @NonNull QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
111 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
112 QName.create(IETF_NETCONF_MONITORING, "format").intern();
113 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
114 QName.create(IETF_NETCONF_MONITORING, "location").intern();
115 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
116 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
117 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
118 QName.create(IETF_NETCONF_MONITORING, "version").intern();
119 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
120 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
122 public static final @NonNull QName IETF_NETCONF_NOTIFICATIONS =
123 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
125 public static final XMLNamespace NETCONF_URI = NETCONF_QNAME.getNamespace();
127 public static final @NonNull NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
129 public static final @NonNull QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
130 public static final @NonNull NodeIdentifier NETCONF_RPC_REPLY_NODEID =
131 NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
133 public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
134 public static final @NonNull QName NETCONF_ERROR_OPTION_QNAME =
135 QName.create(NETCONF_QNAME, "error-option").intern();
136 public static final @NonNull NodeIdentifier NETCONF_ERROR_OPTION_NODEID =
137 NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
138 public static final @NonNull QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
139 public static final @NonNull QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
140 public static final @NonNull NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
141 public static final @NonNull QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
142 public static final @NonNull QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
143 public static final @NonNull NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
144 public static final @NonNull QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
145 public static final @NonNull NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
147 public static final @NonNull QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
148 public static final @NonNull SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
149 public static final @NonNull QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
150 public static final @NonNull NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
151 public static final @NonNull SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
152 public static final @NonNull QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
153 public static final @NonNull NodeIdentifier NETCONF_COPY_CONFIG_NODEID =
154 NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
155 public static final @NonNull SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
157 public static final @NonNull QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
158 private static final @NonNull QName NETCONF_OPERATION_QNAME_LEGACY =
159 NETCONF_OPERATION_QNAME.withoutRevision().intern();
160 public static final @NonNull QName NETCONF_DEFAULT_OPERATION_QNAME =
161 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
162 public static final @NonNull NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
163 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
164 public static final @NonNull QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
165 public static final @NonNull NodeIdentifier NETCONF_EDIT_CONFIG_NODEID =
166 NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
167 public static final @NonNull SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
168 public static final @NonNull QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
169 public static final @NonNull NodeIdentifier NETCONF_GET_CONFIG_NODEID =
170 NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
171 public static final @NonNull SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
172 public static final @NonNull QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
173 public static final @NonNull SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
174 public static final @NonNull QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
175 public static final @NonNull QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
176 public static final @NonNull QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
177 public static final @NonNull NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
178 public static final @NonNull SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
179 public static final @NonNull QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
180 public static final QName YANG_QNAME = null;
181 public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
182 public static final String NETCONF_ACTION = "action";
184 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
185 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
186 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
188 public static final URI NETCONF_CANDIDATE_URI = URI
189 .create("urn:ietf:params:netconf:capability:candidate:1.0");
191 public static final URI NETCONF_NOTIFICATONS_URI = URI
192 .create("urn:ietf:params:netconf:capability:notification:1.0");
194 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
195 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
197 public static final @NonNull QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
198 public static final @NonNull NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
199 public static final @NonNull SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
200 public static final @NonNull QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
201 public static final @NonNull NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
202 public static final @NonNull SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
204 public static final @NonNull NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
206 // Discard changes message
207 public static final @NonNull ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
208 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
210 // Commit changes message
211 public static final @NonNull ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
212 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
215 public static final @NonNull ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
216 .withNodeIdentifier(NETCONF_GET_NODEID).build();
218 // Create-subscription changes message
219 public static final @NonNull ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
220 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
222 public static final @NonNull SchemaPath CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
224 public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
226 public static final @NonNull AnyxmlNode<?> EMPTY_FILTER = buildFilterStructure(getNetconfFilterElement());
229 * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
231 * @param identifier parent path / query
232 * @param ctx mountpoint schema context
233 * @return created DOM structure with subtree filter
235 public static AnyxmlNode<?> toFilterStructure(final YangInstanceIdentifier identifier,
236 final EffectiveModelContext ctx) {
237 final Element element = getNetconfFilterElement();
239 NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
240 } catch (IOException | XMLStreamException e) {
241 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
243 return buildFilterStructure(element);
247 * Creation of the subtree filter structure using list of parent {@link YangInstanceIdentifier}
248 * and specific selection fields. Field paths are relative to parent query path.
250 * @param fieldsFilters list of: parent path and selection fields
251 * @param ctx mountpoint schema context
252 * @return created DOM structure with subtree filter
254 public static AnyxmlNode<?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
255 final EffectiveModelContext ctx) {
256 Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
257 final Element element = getNetconfFilterElement();
259 for (final FieldsFilter filter : fieldsFilters) {
261 NetconfUtil.writeFilter(filter.path(), new DOMResult(element), SchemaPath.ROOT, ctx, filter.fields());
262 } catch (IOException | XMLStreamException e) {
263 throw new IllegalStateException(String.format(
264 "Unable to serialize filter element for path %s with fields: %s",
265 filter.path(), filter.fields()), e);
268 return buildFilterStructure(element);
271 private static Element getNetconfFilterElement() {
272 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
273 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
274 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
279 private static AnyxmlNode<?> buildFilterStructure(final Element element) {
280 return Builders.anyXmlBuilder()
281 .withNodeIdentifier(NETCONF_FILTER_NODEID)
282 .withValue(new DOMSource(element))
286 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
287 throws NetconfDocumentedException {
288 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
289 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
291 if (!inputMsgId.equals(outputMsgId)) {
292 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"", null,
293 ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, ErrorSeverity.ERROR,
294 ImmutableMap.of("actual-message-id", outputMsgId, "expected-message-id", inputMsgId));
298 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
299 if (NetconfMessageUtil.isErrorMessage(output)) {
300 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
304 public static RpcError toRpcError(final NetconfDocumentedException ex) {
305 final StringBuilder infoBuilder = new StringBuilder();
306 final Map<String, String> errorInfo = ex.getErrorInfo();
307 if (errorInfo != null) {
308 for (final Entry<String, String> e : errorInfo.entrySet()) {
309 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
310 .append("</").append(e.getKey()).append('>');
315 return ex.getErrorSeverity() == ErrorSeverity.ERROR
316 ? RpcResultBuilder.newError(ex.getErrorType().toLegacy(), ex.getErrorTag().elementBody(),
317 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
318 : RpcResultBuilder.newWarning(
319 ex.getErrorType().toLegacy(), ex.getErrorTag().elementBody(),
320 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
323 public static NodeIdentifier toId(final PathArgument qname) {
324 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
327 public static NodeIdentifier toId(final QName nodeType) {
328 return new NodeIdentifier(nodeType);
331 public static Element getDataSubtree(final Document doc) {
332 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
335 public static boolean isDataRetrievalOperation(final QName rpc) {
336 return NETCONF_URI.equals(rpc.getNamespace())
337 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
338 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
342 public static @NonNull ContainerNode wrap(final QName name, final DataContainerChild... node) {
343 return wrap(toId(name), node);
346 public static @NonNull ContainerNode wrap(final NodeIdentifier name, final DataContainerChild... node) {
347 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
351 * Create edit-config structure to invoke {@code operation} with {@code lastChildOverride} data on {@code dataPath}.
353 * @param ctx {@link EffectiveModelContext} device's model context
354 * @param dataPath {@link YangInstanceIdentifier} path to data in device's data-store
355 * @param operation Optional of {@link ModifyAction} action to be invoked
356 * @param lastChildOverride Optional of {@code NormalizedNode} data on which action will be invoked
357 * @return {@link DOMSourceAnyxmlNode} containing edit-config structure
359 public static DOMSourceAnyxmlNode createEditConfigAnyxml(
360 final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
361 final Optional<ModifyAction> operation, final Optional<NormalizedNode> lastChildOverride) {
362 if (dataPath.isEmpty()) {
363 Preconditions.checkArgument(lastChildOverride.isPresent(),
364 "Data has to be present when creating structure for top level element");
365 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild,
366 "Data has to be either container or a list node when creating structure for top level element, "
367 + "but was: %s", lastChildOverride.get());
370 final var element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
371 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
372 final var metadata = operation.map(o -> leafMetadata(dataPath, o)).orElse(null);
374 if (lastChildOverride.isPresent()) {
375 // FIXME remove ImmutableNodes.fromInstanceId usage
376 final var configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride.get());
377 NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
379 NetconfUtil.writeNormalizedNode(dataPath, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
381 } catch (final IOException | XMLStreamException e) {
382 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
385 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
389 private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final ModifyAction oper) {
390 final List<PathArgument> args = path.getPathArguments();
391 final Deque<Builder> builders = new ArrayDeque<>(args.size());
393 // Step one: open builders
394 for (PathArgument arg : args) {
395 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
398 // Step two: set the top builder's metadata
399 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
401 // Step three: build the tree
403 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
404 final Builder parent = builders.peek();
405 if (parent != null) {
406 parent.withChild(currentMeta);
413 public static DataContainerChild createEditConfigStructure(final EffectiveModelContext ctx,
414 final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
415 final Optional<NormalizedNode> lastChildOverride) {
416 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
417 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
420 public static @NonNull SchemaPath toPath(final QName rpc) {
421 return SchemaPath.ROOT.createChild(rpc);
424 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
425 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
426 final List<XmlElement> childElements = xmlElement.getChildElements();
427 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
428 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
430 final XmlElement eventTimeElement;
431 final XmlElement notificationElement;
433 if (childElements.get(0).getName().equals(EVENT_TIME)) {
434 eventTimeElement = childElements.get(0);
435 notificationElement = childElements.get(1);
436 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
437 eventTimeElement = childElements.get(1);
438 notificationElement = childElements.get(0);
440 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
444 return new SimpleEntry<>(
445 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
446 notificationElement);
447 } catch (final DocumentedException e) {
448 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
450 } catch (final DateTimeParseException e) {
451 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
452 NetconfNotification.UNKNOWN_EVENT_TIME, e);
453 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
454 notificationElement);
458 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
459 final Document document = XmlUtil.newDocument();
460 final Element rpcNS =
461 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
463 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
464 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
465 rpcNS.appendChild(elementNS);
466 document.appendChild(rpcNS);
467 return new DOMResult(elementNS);
470 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
471 final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
472 final Document document = XmlUtil.newDocument();
473 final Element rpcNS =
474 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
476 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
478 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
479 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
480 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
481 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
483 final Element specificActionElement =
484 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
485 actionData.appendChild(specificActionElement);
486 rpcNS.appendChild(actionNS);
487 document.appendChild(rpcNS);
488 return new DOMResult(specificActionElement);
491 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
492 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
493 if (iterator.hasNext()) {
494 final PathArgument next = iterator.next();
496 final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
497 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
499 if (current.isMixin()) {
500 return prepareActionData(current, actionNS, iterator, document);
503 final QName actualNS = next.getNodeType();
504 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
505 actualNS.getLocalName());
506 if (next instanceof NodeWithValue) {
507 actualElement.setNodeValue(((NodeWithValue<?>) next).getValue().toString());
508 } else if (next instanceof NodeIdentifierWithPredicates) {
509 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
510 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
511 entry.getKey().getLocalName());
512 entryElement.setTextContent(entry.getValue().toString());
513 entryElement.setNodeValue(entry.getValue().toString());
514 actualElement.appendChild(entryElement);
517 actionNS.appendChild(actualElement);
518 return prepareActionData(current, actualElement, iterator, document);
524 @SuppressWarnings("checkstyle:IllegalCatch")
525 public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
526 final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
527 throws IOException, XMLStreamException {
528 final QName inputQName = YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule());
529 // FIXME: eliminate this conversion
530 final SchemaPath inputPath = operationPath.asSchemaPath().createChild(inputQName);
532 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
534 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
535 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, inputPath)) {
536 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
537 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, inputPath)) {
538 final Collection<DataContainerChild> value = normalized.body();
539 normalizedNodeWriter.write(value);
540 normalizedNodeWriter.flush();
546 } catch (final Exception e) {
547 LOG.warn("Unable to close resource properly", e);
552 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
553 return RpcResultBuilder.<NetconfMessage>failed()
554 .withRpcError(toRpcError(new NetconfDocumentedException(message.getException().getMessage(),
555 ErrorType.APPLICATION, ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR)))