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.ErrorType;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.common.RpcError;
58 import org.opendaylight.yangtools.yang.common.RpcResult;
59 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
60 import org.opendaylight.yangtools.yang.common.XMLNamespace;
61 import org.opendaylight.yangtools.yang.common.YangConstants;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
67 import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
71 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
73 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
74 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
75 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
76 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
77 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
78 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
79 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
80 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
81 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84 import org.w3c.dom.Document;
85 import org.w3c.dom.Element;
87 public final class NetconfMessageTransformUtil {
89 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
91 public static final String MESSAGE_ID_PREFIX = "m";
92 public static final String MESSAGE_ID_ATTR = "message-id";
94 public static final @NonNull QName CREATE_SUBSCRIPTION_RPC_QNAME =
95 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
96 private static final String SUBTREE = "subtree";
98 // Blank document used for creation of new DOM nodes
99 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
100 public static final String EVENT_TIME = "eventTime";
102 private NetconfMessageTransformUtil() {
106 public static final @NonNull QName IETF_NETCONF_MONITORING =
107 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
108 public static final @NonNull QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
109 public static final @NonNull QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
110 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
111 QName.create(IETF_NETCONF_MONITORING, "format").intern();
112 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
113 QName.create(IETF_NETCONF_MONITORING, "location").intern();
114 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
115 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
116 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
117 QName.create(IETF_NETCONF_MONITORING, "version").intern();
118 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
119 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
121 public static final @NonNull QName IETF_NETCONF_NOTIFICATIONS =
122 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
124 public static final XMLNamespace NETCONF_URI = NETCONF_QNAME.getNamespace();
126 public static final @NonNull NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
128 public static final @NonNull QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
129 public static final @NonNull NodeIdentifier NETCONF_RPC_REPLY_NODEID =
130 NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
132 public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
133 public static final @NonNull QName NETCONF_ERROR_OPTION_QNAME =
134 QName.create(NETCONF_QNAME, "error-option").intern();
135 public static final @NonNull NodeIdentifier NETCONF_ERROR_OPTION_NODEID =
136 NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
137 public static final @NonNull QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
138 public static final @NonNull QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
139 public static final @NonNull NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
140 public static final @NonNull QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
141 public static final @NonNull QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
142 public static final @NonNull NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
143 public static final @NonNull QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
144 public static final @NonNull NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
146 public static final @NonNull QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
147 public static final @NonNull SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
148 public static final @NonNull QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
149 public static final @NonNull NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
150 public static final @NonNull SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
151 public static final @NonNull QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
152 public static final @NonNull NodeIdentifier NETCONF_COPY_CONFIG_NODEID =
153 NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
154 public static final @NonNull SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
156 public static final @NonNull QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
157 private static final @NonNull QName NETCONF_OPERATION_QNAME_LEGACY =
158 NETCONF_OPERATION_QNAME.withoutRevision().intern();
159 public static final @NonNull QName NETCONF_DEFAULT_OPERATION_QNAME =
160 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
161 public static final @NonNull NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
162 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
163 public static final @NonNull QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
164 public static final @NonNull NodeIdentifier NETCONF_EDIT_CONFIG_NODEID =
165 NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
166 public static final @NonNull SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
167 public static final @NonNull QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
168 public static final @NonNull NodeIdentifier NETCONF_GET_CONFIG_NODEID =
169 NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
170 public static final @NonNull SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
171 public static final @NonNull QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
172 public static final @NonNull SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
173 public static final @NonNull QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
174 public static final @NonNull QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
175 public static final @NonNull QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
176 public static final @NonNull NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
177 public static final @NonNull SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
178 public static final @NonNull QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
179 public static final QName YANG_QNAME = null;
180 public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
181 public static final String NETCONF_ACTION = "action";
183 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
184 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
185 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
187 public static final URI NETCONF_CANDIDATE_URI = URI
188 .create("urn:ietf:params:netconf:capability:candidate:1.0");
190 public static final URI NETCONF_NOTIFICATONS_URI = URI
191 .create("urn:ietf:params:netconf:capability:notification:1.0");
193 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
194 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
196 public static final @NonNull QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
197 public static final @NonNull NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
198 public static final @NonNull SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
199 public static final @NonNull QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
200 public static final @NonNull NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
201 public static final @NonNull SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
203 public static final @NonNull NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
205 // Discard changes message
206 public static final @NonNull ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
207 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
209 // Commit changes message
210 public static final @NonNull ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
211 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
214 public static final @NonNull ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
215 .withNodeIdentifier(NETCONF_GET_NODEID).build();
217 // Create-subscription changes message
218 public static final @NonNull ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
219 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
221 public static final @NonNull SchemaPath CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
223 public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
225 public static final @NonNull AnyxmlNode<?> EMPTY_FILTER = buildFilterStructure(getNetconfFilterElement());
228 * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
230 * @param identifier parent path / query
231 * @param ctx mountpoint schema context
232 * @return created DOM structure with subtree filter
234 public static AnyxmlNode<?> toFilterStructure(final YangInstanceIdentifier identifier,
235 final EffectiveModelContext ctx) {
236 final Element element = getNetconfFilterElement();
238 NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
239 } catch (IOException | XMLStreamException e) {
240 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
242 return buildFilterStructure(element);
246 * Creation of the subtree filter structure using list of parent {@link YangInstanceIdentifier}
247 * and specific selection fields. Field paths are relative to parent query path.
249 * @param fieldsFilters list of: parent path and selection fields
250 * @param ctx mountpoint schema context
251 * @return created DOM structure with subtree filter
253 public static AnyxmlNode<?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
254 final EffectiveModelContext ctx) {
255 Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
256 final Element element = getNetconfFilterElement();
258 for (final FieldsFilter filter : fieldsFilters) {
260 NetconfUtil.writeFilter(filter.path(), new DOMResult(element), SchemaPath.ROOT, ctx, filter.fields());
261 } catch (IOException | XMLStreamException e) {
262 throw new IllegalStateException(String.format(
263 "Unable to serialize filter element for path %s with fields: %s",
264 filter.path(), filter.fields()), e);
267 return buildFilterStructure(element);
270 private static Element getNetconfFilterElement() {
271 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
272 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
273 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
278 private static AnyxmlNode<?> buildFilterStructure(final Element element) {
279 return Builders.anyXmlBuilder()
280 .withNodeIdentifier(NETCONF_FILTER_NODEID)
281 .withValue(new DOMSource(element))
285 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
286 throws NetconfDocumentedException {
287 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
288 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
290 if (!inputMsgId.equals(outputMsgId)) {
291 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"", null,
292 ErrorType.PROTOCOL, NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE, ErrorSeverity.ERROR,
293 ImmutableMap.of("actual-message-id", outputMsgId, "expected-message-id", inputMsgId));
297 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
298 if (NetconfMessageUtil.isErrorMessage(output)) {
299 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
303 public static RpcError toRpcError(final NetconfDocumentedException ex) {
304 final StringBuilder infoBuilder = new StringBuilder();
305 final Map<String, String> errorInfo = ex.getErrorInfo();
306 if (errorInfo != null) {
307 for (final Entry<String, String> e : errorInfo.entrySet()) {
308 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
309 .append("</").append(e.getKey()).append('>');
314 return ex.getErrorSeverity() == ErrorSeverity.ERROR
315 ? RpcResultBuilder.newError(ex.getErrorType().toLegacy(), ex.getErrorTag().getTagValue(),
316 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
317 : RpcResultBuilder.newWarning(
318 ex.getErrorType().toLegacy(), ex.getErrorTag().getTagValue(),
319 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
322 public static NodeIdentifier toId(final PathArgument qname) {
323 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
326 public static NodeIdentifier toId(final QName nodeType) {
327 return new NodeIdentifier(nodeType);
330 public static Element getDataSubtree(final Document doc) {
331 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
334 public static boolean isDataRetrievalOperation(final QName rpc) {
335 return NETCONF_URI.equals(rpc.getNamespace())
336 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
337 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
341 public static @NonNull ContainerNode wrap(final QName name, final DataContainerChild... node) {
342 return wrap(toId(name), node);
345 public static @NonNull ContainerNode wrap(final NodeIdentifier name, final DataContainerChild... node) {
346 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
349 public static DOMSourceAnyxmlNode createEditConfigAnyxml(
350 final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
351 final Optional<ModifyAction> operation, final Optional<NormalizedNode> lastChildOverride) {
352 final NormalizedNode configContent;
353 final NormalizedMetadata metadata;
354 if (dataPath.isEmpty()) {
355 Preconditions.checkArgument(lastChildOverride.isPresent(),
356 "Data has to be present when creating structure for top level element");
357 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild,
358 "Data has to be either container or a list node when creating structure for top level element, "
359 + "but was: %s", lastChildOverride.get());
360 configContent = lastChildOverride.get();
363 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride);
364 metadata = operation.map(oper -> leafMetadata(dataPath, oper)).orElse(null);
367 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
368 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
371 NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
372 } catch (IOException | XMLStreamException e) {
373 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
376 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
380 private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final ModifyAction oper) {
381 final List<PathArgument> args = path.getPathArguments();
382 final Deque<Builder> builders = new ArrayDeque<>(args.size());
384 // Step one: open builders
385 for (PathArgument arg : args) {
386 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
389 // Step two: set the top builder's metadata
390 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
392 // Step three: build the tree
394 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
395 final Builder parent = builders.peek();
396 if (parent != null) {
397 parent.withChild(currentMeta);
404 public static DataContainerChild createEditConfigStructure(final EffectiveModelContext ctx,
405 final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
406 final Optional<NormalizedNode> lastChildOverride) {
407 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
408 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
411 public static @NonNull SchemaPath toPath(final QName rpc) {
412 return SchemaPath.ROOT.createChild(rpc);
415 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
416 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
417 final List<XmlElement> childElements = xmlElement.getChildElements();
418 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
419 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
421 final XmlElement eventTimeElement;
422 final XmlElement notificationElement;
424 if (childElements.get(0).getName().equals(EVENT_TIME)) {
425 eventTimeElement = childElements.get(0);
426 notificationElement = childElements.get(1);
427 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
428 eventTimeElement = childElements.get(1);
429 notificationElement = childElements.get(0);
431 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
435 return new SimpleEntry<>(
436 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
437 notificationElement);
438 } catch (final DocumentedException e) {
439 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
441 } catch (final DateTimeParseException e) {
442 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
443 NetconfNotification.UNKNOWN_EVENT_TIME, e);
444 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
445 notificationElement);
449 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
450 final Document document = XmlUtil.newDocument();
451 final Element rpcNS =
452 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
454 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
455 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
456 rpcNS.appendChild(elementNS);
457 document.appendChild(rpcNS);
458 return new DOMResult(elementNS);
461 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
462 final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
463 final Document document = XmlUtil.newDocument();
464 final Element rpcNS =
465 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
467 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
469 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
470 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
471 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
472 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
474 final Element specificActionElement =
475 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
476 actionData.appendChild(specificActionElement);
477 rpcNS.appendChild(actionNS);
478 document.appendChild(rpcNS);
479 return new DOMResult(specificActionElement);
482 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
483 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
484 if (iterator.hasNext()) {
485 final PathArgument next = iterator.next();
487 final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
488 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
490 if (current.isMixin()) {
491 return prepareActionData(current, actionNS, iterator, document);
494 final QName actualNS = next.getNodeType();
495 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
496 actualNS.getLocalName());
497 if (next instanceof NodeWithValue) {
498 actualElement.setNodeValue(((NodeWithValue<?>) next).getValue().toString());
499 } else if (next instanceof NodeIdentifierWithPredicates) {
500 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
501 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
502 entry.getKey().getLocalName());
503 entryElement.setTextContent(entry.getValue().toString());
504 entryElement.setNodeValue(entry.getValue().toString());
505 actualElement.appendChild(entryElement);
508 actionNS.appendChild(actualElement);
509 return prepareActionData(current, actualElement, iterator, document);
515 @SuppressWarnings("checkstyle:IllegalCatch")
516 public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
517 final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
518 throws IOException, XMLStreamException {
519 final QName inputQName = YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule());
520 // FIXME: eliminate this conversion
521 final SchemaPath inputPath = operationPath.asSchemaPath().createChild(inputQName);
523 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
525 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
526 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, inputPath)) {
527 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
528 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, inputPath)) {
529 final Collection<DataContainerChild> value = normalized.body();
530 normalizedNodeWriter.write(value);
531 normalizedNodeWriter.flush();
537 } catch (final Exception e) {
538 LOG.warn("Unable to close resource properly", e);
543 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
544 return RpcResultBuilder.<NetconfMessage>failed()
545 .withRpcError(toRpcError(new NetconfDocumentedException(message.getException().getMessage(),
546 ErrorType.APPLICATION, DocumentedException.ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR)))