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.NodeContainerProxy;
47 import org.opendaylight.netconf.util.messages.NetconfMessageUtil;
48 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
49 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
50 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
51 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
52 import org.opendaylight.yangtools.rfc7952.data.api.NormalizedMetadata;
53 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata;
54 import org.opendaylight.yangtools.rfc7952.data.util.ImmutableNormalizedMetadata.Builder;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.RpcError;
57 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
58 import org.opendaylight.yangtools.yang.common.RpcResult;
59 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
60 import org.opendaylight.yangtools.yang.common.YangConstants;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
66 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
71 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
72 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
73 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
74 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
75 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
76 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
77 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
79 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
80 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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 URI 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 DataContainerChild<?, ?> EMPTY_FILTER;
229 final Element element = getNetconfFilterElement();
230 EMPTY_FILTER = buildFilterStructure(element);
234 * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
236 * @param identifier parent path / query
237 * @param ctx mountpoint schema context
238 * @return created DOM structure with subtree filter
240 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
241 final EffectiveModelContext ctx) {
242 final Element element = getNetconfFilterElement();
244 NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
245 } catch (IOException | XMLStreamException e) {
246 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
248 return buildFilterStructure(element);
252 * Creation of the subtree filter structure using list of parent {@link YangInstanceIdentifier}
253 * and specific selection fields. Field paths are relative to parent query path.
255 * @param fieldsFilters list of: parent path and selection fields
256 * @param ctx mountpoint schema context
257 * @return created DOM structure with subtree filter
259 public static DataContainerChild<?, ?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
260 final EffectiveModelContext ctx) {
261 Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
262 final Element element = getNetconfFilterElement();
264 for (final FieldsFilter filter : fieldsFilters) {
266 NetconfUtil.writeFilter(filter.path(), new DOMResult(element), SchemaPath.ROOT, ctx, filter.fields());
267 } catch (IOException | XMLStreamException e) {
268 throw new IllegalStateException(String.format(
269 "Unable to serialize filter element for path %s with fields: %s",
270 filter.path(), filter.fields()), e);
273 return buildFilterStructure(element);
276 private static Element getNetconfFilterElement() {
277 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
278 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
279 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
284 private static DataContainerChild<?, ?> buildFilterStructure(final Element element) {
285 return Builders.anyXmlBuilder()
286 .withNodeIdentifier(NETCONF_FILTER_NODEID)
287 .withValue(new DOMSource(element))
291 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
292 throws NetconfDocumentedException {
293 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
294 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
296 if (!inputMsgId.equals(outputMsgId)) {
297 final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
298 .put("actual-message-id", outputMsgId)
299 .put("expected-message-id", inputMsgId)
302 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
303 null, NetconfDocumentedException.ErrorType.PROTOCOL,
304 NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
305 NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
309 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
310 if (NetconfMessageUtil.isErrorMessage(output)) {
311 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
315 public static RpcError toRpcError(final NetconfDocumentedException ex) {
316 final StringBuilder infoBuilder = new StringBuilder();
317 final Map<String, String> errorInfo = ex.getErrorInfo();
318 if (errorInfo != null) {
319 for (final Entry<String, String> e : errorInfo.entrySet()) {
320 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
321 .append("</").append(e.getKey()).append('>');
326 final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
327 return severity == ErrorSeverity.ERROR
328 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
329 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
330 : RpcResultBuilder.newWarning(
331 toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
332 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
335 private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
338 return RpcError.ErrorSeverity.WARNING;
340 return RpcError.ErrorSeverity.ERROR;
344 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
347 return RpcError.ErrorType.PROTOCOL;
349 return RpcError.ErrorType.RPC;
351 return RpcError.ErrorType.TRANSPORT;
353 return RpcError.ErrorType.APPLICATION;
357 public static NodeIdentifier toId(final PathArgument qname) {
358 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
361 public static NodeIdentifier toId(final QName nodeType) {
362 return new NodeIdentifier(nodeType);
365 public static Element getDataSubtree(final Document doc) {
366 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
369 public static boolean isDataRetrievalOperation(final QName rpc) {
370 return NETCONF_URI.equals(rpc.getNamespace())
371 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
372 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
375 public static @NonNull ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
376 return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
379 public static @NonNull ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
380 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
384 public static @NonNull ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
385 return wrap(toId(name), node);
388 public static @NonNull ContainerNode wrap(final NodeIdentifier name, final DataContainerChild<?, ?>... node) {
389 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
392 public static DOMSourceAnyxmlNode createEditConfigAnyxml(
393 final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
394 final Optional<ModifyAction> operation,
395 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
396 final NormalizedNode<?, ?> configContent;
397 final NormalizedMetadata metadata;
398 if (dataPath.isEmpty()) {
399 Preconditions.checkArgument(lastChildOverride.isPresent(),
400 "Data has to be present when creating structure for top level element");
401 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
402 "Data has to be either container or a list node when creating structure for top level element, "
403 + "but was: %s", lastChildOverride.get());
404 configContent = lastChildOverride.get();
407 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride);
408 metadata = operation.map(oper -> leafMetadata(dataPath, oper)).orElse(null);
411 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
412 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
415 NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
416 } catch (IOException | XMLStreamException e) {
417 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
420 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
424 private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final ModifyAction oper) {
425 final List<PathArgument> args = path.getPathArguments();
426 final Deque<Builder> builders = new ArrayDeque<>(args.size());
428 // Step one: open builders
429 for (PathArgument arg : args) {
430 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
433 // Step two: set the top builder's metadata
434 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
436 // Step three: build the tree
438 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
439 final Builder parent = builders.peek();
440 if (parent != null) {
441 parent.withChild(currentMeta);
448 public static DataContainerChild<?, ?> createEditConfigStructure(final EffectiveModelContext ctx,
449 final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
450 final Optional<NormalizedNode<?, ?>> lastChildOverride) {
451 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
452 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
455 public static @NonNull SchemaPath toPath(final QName rpc) {
456 return SchemaPath.ROOT.createChild(rpc);
459 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
460 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
461 final List<XmlElement> childElements = xmlElement.getChildElements();
462 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
463 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
465 final XmlElement eventTimeElement;
466 final XmlElement notificationElement;
468 if (childElements.get(0).getName().equals(EVENT_TIME)) {
469 eventTimeElement = childElements.get(0);
470 notificationElement = childElements.get(1);
471 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
472 eventTimeElement = childElements.get(1);
473 notificationElement = childElements.get(0);
475 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
479 return new SimpleEntry<>(
480 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
481 notificationElement);
482 } catch (final DocumentedException e) {
483 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
485 } catch (final DateTimeParseException e) {
486 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
487 NetconfNotification.UNKNOWN_EVENT_TIME, e);
488 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
489 notificationElement);
493 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
494 final Document document = XmlUtil.newDocument();
495 final Element rpcNS =
496 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
498 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
499 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
500 rpcNS.appendChild(elementNS);
501 document.appendChild(rpcNS);
502 return new DOMResult(elementNS);
505 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
506 final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
507 final Document document = XmlUtil.newDocument();
508 final Element rpcNS =
509 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
511 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
513 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
514 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
515 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
516 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
518 final Element specificActionElement =
519 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
520 actionData.appendChild(specificActionElement);
521 rpcNS.appendChild(actionNS);
522 document.appendChild(rpcNS);
523 return new DOMResult(specificActionElement);
526 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
527 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
528 if (iterator.hasNext()) {
529 final PathArgument next = iterator.next();
531 final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
532 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
534 if (current.isMixin()) {
535 return prepareActionData(current, actionNS, iterator, document);
538 final QName actualNS = next.getNodeType();
539 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
540 actualNS.getLocalName());
541 if (next instanceof NodeWithValue) {
542 actualElement.setNodeValue(((NodeWithValue<?>) next).getValue().toString());
543 } else if (next instanceof NodeIdentifierWithPredicates) {
544 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
545 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
546 entry.getKey().getLocalName());
547 entryElement.setTextContent(entry.getValue().toString());
548 entryElement.setNodeValue(entry.getValue().toString());
549 actualElement.appendChild(entryElement);
552 actionNS.appendChild(actualElement);
553 return prepareActionData(current, actualElement, iterator, document);
559 @SuppressWarnings("checkstyle:IllegalCatch")
560 public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
561 final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
562 throws IOException, XMLStreamException {
563 final QName inputQName = YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule());
564 // FIXME: eliminate this conversion
565 final SchemaPath inputPath = operationPath.asSchemaPath().createChild(inputQName);
567 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
569 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
570 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, inputPath)) {
571 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
572 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, inputPath)) {
573 final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
574 normalizedNodeWriter.write(value);
575 normalizedNodeWriter.flush();
581 } catch (final Exception e) {
582 LOG.warn("Unable to close resource properly", e);
587 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
588 return RpcResultBuilder.<NetconfMessage>failed()
591 new NetconfDocumentedException(
592 message.getException().getMessage(),
593 DocumentedException.ErrorType.APPLICATION,
594 DocumentedException.ErrorTag.MALFORMED_MESSAGE,
595 DocumentedException.ErrorSeverity.ERROR)))