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.QName;
56 import org.opendaylight.yangtools.yang.common.RpcError;
57 import org.opendaylight.yangtools.yang.common.RpcResult;
58 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
59 import org.opendaylight.yangtools.yang.common.XMLNamespace;
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.AnyxmlNode;
67 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
70 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
72 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
73 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
74 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
75 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaOrderedNormalizedNodeWriter;
76 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
77 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
78 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
79 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
80 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83 import org.w3c.dom.Document;
84 import org.w3c.dom.Element;
86 public final class NetconfMessageTransformUtil {
88 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
90 public static final String MESSAGE_ID_PREFIX = "m";
91 public static final String MESSAGE_ID_ATTR = "message-id";
93 public static final @NonNull QName CREATE_SUBSCRIPTION_RPC_QNAME =
94 QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
95 private static final String SUBTREE = "subtree";
97 // Blank document used for creation of new DOM nodes
98 private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
99 public static final String EVENT_TIME = "eventTime";
101 private NetconfMessageTransformUtil() {
105 public static final @NonNull QName IETF_NETCONF_MONITORING =
106 QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
107 public static final @NonNull QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
108 public static final @NonNull QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
109 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
110 QName.create(IETF_NETCONF_MONITORING, "format").intern();
111 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
112 QName.create(IETF_NETCONF_MONITORING, "location").intern();
113 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
114 QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
115 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
116 QName.create(IETF_NETCONF_MONITORING, "version").intern();
117 public static final @NonNull QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
118 QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
120 public static final @NonNull QName IETF_NETCONF_NOTIFICATIONS =
121 QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
123 public static final XMLNamespace NETCONF_URI = NETCONF_QNAME.getNamespace();
125 public static final @NonNull NodeIdentifier NETCONF_DATA_NODEID = NodeIdentifier.create(NETCONF_DATA_QNAME);
127 public static final @NonNull QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply").intern();
128 public static final @NonNull NodeIdentifier NETCONF_RPC_REPLY_NODEID =
129 NodeIdentifier.create(NETCONF_RPC_REPLY_QNAME);
131 public static final @NonNull QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok").intern();
132 public static final @NonNull QName NETCONF_ERROR_OPTION_QNAME =
133 QName.create(NETCONF_QNAME, "error-option").intern();
134 public static final @NonNull NodeIdentifier NETCONF_ERROR_OPTION_NODEID =
135 NodeIdentifier.create(NETCONF_ERROR_OPTION_QNAME);
136 public static final @NonNull QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running").intern();
137 public static final @NonNull QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source").intern();
138 public static final @NonNull NodeIdentifier NETCONF_SOURCE_NODEID = NodeIdentifier.create(NETCONF_SOURCE_QNAME);
139 public static final @NonNull QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate").intern();
140 public static final @NonNull QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target").intern();
141 public static final @NonNull NodeIdentifier NETCONF_TARGET_NODEID = NodeIdentifier.create(NETCONF_TARGET_QNAME);
142 public static final @NonNull QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config").intern();
143 public static final @NonNull NodeIdentifier NETCONF_CONFIG_NODEID = NodeIdentifier.create(NETCONF_CONFIG_QNAME);
145 public static final @NonNull QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit").intern();
146 public static final @NonNull SchemaPath NETCONF_COMMIT_PATH = toPath(NETCONF_COMMIT_QNAME);
147 public static final @NonNull QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
148 public static final @NonNull NodeIdentifier NETCONF_VALIDATE_NODEID = NodeIdentifier.create(NETCONF_VALIDATE_QNAME);
149 public static final @NonNull SchemaPath NETCONF_VALIDATE_PATH = toPath(NETCONF_VALIDATE_QNAME);
150 public static final @NonNull QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
151 public static final @NonNull NodeIdentifier NETCONF_COPY_CONFIG_NODEID =
152 NodeIdentifier.create(NETCONF_COPY_CONFIG_QNAME);
153 public static final @NonNull SchemaPath NETCONF_COPY_CONFIG_PATH = toPath(NETCONF_COPY_CONFIG_QNAME);
155 public static final @NonNull QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
156 private static final @NonNull QName NETCONF_OPERATION_QNAME_LEGACY =
157 NETCONF_OPERATION_QNAME.withoutRevision().intern();
158 public static final @NonNull QName NETCONF_DEFAULT_OPERATION_QNAME =
159 QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
160 public static final @NonNull NodeIdentifier NETCONF_DEFAULT_OPERATION_NODEID =
161 NodeIdentifier.create(NETCONF_DEFAULT_OPERATION_QNAME);
162 public static final @NonNull QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
163 public static final @NonNull NodeIdentifier NETCONF_EDIT_CONFIG_NODEID =
164 NodeIdentifier.create(NETCONF_EDIT_CONFIG_QNAME);
165 public static final @NonNull SchemaPath NETCONF_EDIT_CONFIG_PATH = toPath(NETCONF_EDIT_CONFIG_QNAME);
166 public static final @NonNull QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
167 public static final @NonNull NodeIdentifier NETCONF_GET_CONFIG_NODEID =
168 NodeIdentifier.create(NETCONF_GET_CONFIG_QNAME);
169 public static final @NonNull SchemaPath NETCONF_GET_CONFIG_PATH = toPath(NETCONF_GET_CONFIG_QNAME);
170 public static final @NonNull QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
171 public static final @NonNull SchemaPath NETCONF_DISCARD_CHANGES_PATH = toPath(NETCONF_DISCARD_CHANGES_QNAME);
172 public static final @NonNull QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type").intern();
173 public static final @NonNull QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter").intern();
174 public static final @NonNull QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get").intern();
175 public static final @NonNull NodeIdentifier NETCONF_GET_NODEID = NodeIdentifier.create(NETCONF_GET_QNAME);
176 public static final @NonNull SchemaPath NETCONF_GET_PATH = toPath(NETCONF_GET_QNAME);
177 public static final @NonNull QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc").intern();
178 public static final QName YANG_QNAME = null;
179 public static final URI NETCONF_ACTION_NAMESPACE = URI.create("urn:ietf:params:xml:ns:yang:1");
180 public static final String NETCONF_ACTION = "action";
182 public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
183 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
184 public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
186 public static final URI NETCONF_CANDIDATE_URI = URI
187 .create("urn:ietf:params:netconf:capability:candidate:1.0");
189 public static final URI NETCONF_NOTIFICATONS_URI = URI
190 .create("urn:ietf:params:netconf:capability:notification:1.0");
192 public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
193 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
195 public static final @NonNull QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock").intern();
196 public static final @NonNull NodeIdentifier NETCONF_LOCK_NODEID = NodeIdentifier.create(NETCONF_LOCK_QNAME);
197 public static final @NonNull SchemaPath NETCONF_LOCK_PATH = toPath(NETCONF_LOCK_QNAME);
198 public static final @NonNull QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock").intern();
199 public static final @NonNull NodeIdentifier NETCONF_UNLOCK_NODEID = NodeIdentifier.create(NETCONF_UNLOCK_QNAME);
200 public static final @NonNull SchemaPath NETCONF_UNLOCK_PATH = toPath(NETCONF_UNLOCK_QNAME);
202 public static final @NonNull NodeIdentifier EDIT_CONTENT_NODEID = NodeIdentifier.create(EditContent.QNAME);
204 // Discard changes message
205 public static final @NonNull ContainerNode DISCARD_CHANGES_RPC_CONTENT = Builders.containerBuilder()
206 .withNodeIdentifier(NodeIdentifier.create(NETCONF_DISCARD_CHANGES_QNAME)).build();
208 // Commit changes message
209 public static final @NonNull ContainerNode COMMIT_RPC_CONTENT = Builders.containerBuilder()
210 .withNodeIdentifier(NodeIdentifier.create(NETCONF_COMMIT_QNAME)).build();
213 public static final @NonNull ContainerNode GET_RPC_CONTENT = Builders.containerBuilder()
214 .withNodeIdentifier(NETCONF_GET_NODEID).build();
216 // Create-subscription changes message
217 public static final @NonNull ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT = Builders.containerBuilder()
218 .withNodeIdentifier(NodeIdentifier.create(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
220 public static final @NonNull SchemaPath CREATE_SUBSCRIPTION_RPC_PATH = toPath(CREATE_SUBSCRIPTION_RPC_QNAME);
222 public static final @NonNull NodeIdentifier NETCONF_FILTER_NODEID = NodeIdentifier.create(NETCONF_FILTER_QNAME);
224 public static final @NonNull AnyxmlNode<?> EMPTY_FILTER = buildFilterStructure(getNetconfFilterElement());
227 * Creation of the subtree filter structure using {@link YangInstanceIdentifier} path.
229 * @param identifier parent path / query
230 * @param ctx mountpoint schema context
231 * @return created DOM structure with subtree filter
233 public static AnyxmlNode<?> toFilterStructure(final YangInstanceIdentifier identifier,
234 final EffectiveModelContext ctx) {
235 final Element element = getNetconfFilterElement();
237 NetconfUtil.writeFilter(identifier, new DOMResult(element), SchemaPath.ROOT, ctx);
238 } catch (IOException | XMLStreamException e) {
239 throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
241 return buildFilterStructure(element);
245 * Creation of the subtree filter structure using list of parent {@link YangInstanceIdentifier}
246 * and specific selection fields. Field paths are relative to parent query path.
248 * @param fieldsFilters list of: parent path and selection fields
249 * @param ctx mountpoint schema context
250 * @return created DOM structure with subtree filter
252 public static AnyxmlNode<?> toFilterStructure(final List<FieldsFilter> fieldsFilters,
253 final EffectiveModelContext ctx) {
254 Preconditions.checkState(!fieldsFilters.isEmpty(), "An empty list of subtree filters is not allowed");
255 final Element element = getNetconfFilterElement();
257 for (final FieldsFilter filter : fieldsFilters) {
259 NetconfUtil.writeFilter(filter.path(), new DOMResult(element), SchemaPath.ROOT, ctx, filter.fields());
260 } catch (IOException | XMLStreamException e) {
261 throw new IllegalStateException(String.format(
262 "Unable to serialize filter element for path %s with fields: %s",
263 filter.path(), filter.fields()), e);
266 return buildFilterStructure(element);
269 private static Element getNetconfFilterElement() {
270 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
271 Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
272 element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
277 private static AnyxmlNode<?> buildFilterStructure(final Element element) {
278 return Builders.anyXmlBuilder()
279 .withNodeIdentifier(NETCONF_FILTER_NODEID)
280 .withValue(new DOMSource(element))
284 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
285 throws NetconfDocumentedException {
286 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
287 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
289 if (!inputMsgId.equals(outputMsgId)) {
290 final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
291 .put("actual-message-id", outputMsgId)
292 .put("expected-message-id", inputMsgId)
295 throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
296 null, NetconfDocumentedException.ErrorType.PROTOCOL,
297 NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
298 ErrorSeverity.ERROR, errorInfo);
302 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
303 if (NetconfMessageUtil.isErrorMessage(output)) {
304 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
308 public static RpcError toRpcError(final NetconfDocumentedException ex) {
309 final StringBuilder infoBuilder = new StringBuilder();
310 final Map<String, String> errorInfo = ex.getErrorInfo();
311 if (errorInfo != null) {
312 for (final Entry<String, String> e : errorInfo.entrySet()) {
313 infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
314 .append("</").append(e.getKey()).append('>');
319 return ex.getErrorSeverity() == ErrorSeverity.ERROR
320 ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
321 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
322 : RpcResultBuilder.newWarning(
323 toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
324 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
327 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
330 return RpcError.ErrorType.PROTOCOL;
332 return RpcError.ErrorType.RPC;
334 return RpcError.ErrorType.TRANSPORT;
336 return RpcError.ErrorType.APPLICATION;
340 public static NodeIdentifier toId(final PathArgument qname) {
341 return qname instanceof NodeIdentifier ? (NodeIdentifier) qname : toId(qname.getNodeType());
344 public static NodeIdentifier toId(final QName nodeType) {
345 return new NodeIdentifier(nodeType);
348 public static Element getDataSubtree(final Document doc) {
349 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
352 public static boolean isDataRetrievalOperation(final QName rpc) {
353 return NETCONF_URI.equals(rpc.getNamespace())
354 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
355 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
359 public static @NonNull ContainerNode wrap(final QName name, final DataContainerChild... node) {
360 return wrap(toId(name), node);
363 public static @NonNull ContainerNode wrap(final NodeIdentifier name, final DataContainerChild... node) {
364 return Builders.containerBuilder().withNodeIdentifier(name).withValue(ImmutableList.copyOf(node)).build();
367 public static DOMSourceAnyxmlNode createEditConfigAnyxml(
368 final EffectiveModelContext ctx, final YangInstanceIdentifier dataPath,
369 final Optional<ModifyAction> operation, final Optional<NormalizedNode> lastChildOverride) {
370 final NormalizedNode configContent;
371 final NormalizedMetadata metadata;
372 if (dataPath.isEmpty()) {
373 Preconditions.checkArgument(lastChildOverride.isPresent(),
374 "Data has to be present when creating structure for top level element");
375 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild,
376 "Data has to be either container or a list node when creating structure for top level element, "
377 + "but was: %s", lastChildOverride.get());
378 configContent = lastChildOverride.get();
381 configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride);
382 metadata = operation.map(oper -> leafMetadata(dataPath, oper)).orElse(null);
385 final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
386 Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
389 NetconfUtil.writeNormalizedNode(configContent, metadata, new DOMResult(element), SchemaPath.ROOT, ctx);
390 } catch (IOException | XMLStreamException e) {
391 throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
394 return Builders.anyXmlBuilder().withNodeIdentifier(NETCONF_CONFIG_NODEID).withValue(new DOMSource(element))
398 private static NormalizedMetadata leafMetadata(final YangInstanceIdentifier path, final ModifyAction oper) {
399 final List<PathArgument> args = path.getPathArguments();
400 final Deque<Builder> builders = new ArrayDeque<>(args.size());
402 // Step one: open builders
403 for (PathArgument arg : args) {
404 builders.push(ImmutableNormalizedMetadata.builder().withIdentifier(arg));
407 // Step two: set the top builder's metadata
408 builders.peek().withAnnotation(NETCONF_OPERATION_QNAME_LEGACY, oper.toString().toLowerCase(Locale.US));
410 // Step three: build the tree
412 final ImmutableNormalizedMetadata currentMeta = builders.pop().build();
413 final Builder parent = builders.peek();
414 if (parent != null) {
415 parent.withChild(currentMeta);
422 public static DataContainerChild createEditConfigStructure(final EffectiveModelContext ctx,
423 final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
424 final Optional<NormalizedNode> lastChildOverride) {
425 return Builders.choiceBuilder().withNodeIdentifier(EDIT_CONTENT_NODEID)
426 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
429 public static @NonNull SchemaPath toPath(final QName rpc) {
430 return SchemaPath.ROOT.createChild(rpc);
433 public static Map.Entry<Instant, XmlElement> stripNotification(final NetconfMessage message) {
434 final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
435 final List<XmlElement> childElements = xmlElement.getChildElements();
436 Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
437 + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
439 final XmlElement eventTimeElement;
440 final XmlElement notificationElement;
442 if (childElements.get(0).getName().equals(EVENT_TIME)) {
443 eventTimeElement = childElements.get(0);
444 notificationElement = childElements.get(1);
445 } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
446 eventTimeElement = childElements.get(1);
447 notificationElement = childElements.get(0);
449 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
453 return new SimpleEntry<>(
454 NetconfNotification.RFC3339_DATE_PARSER.apply(eventTimeElement.getTextContent()).toInstant(),
455 notificationElement);
456 } catch (final DocumentedException e) {
457 throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message,
459 } catch (final DateTimeParseException e) {
460 LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
461 NetconfNotification.UNKNOWN_EVENT_TIME, e);
462 return new SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME.toInstant(),
463 notificationElement);
467 public static DOMResult prepareDomResultForRpcRequest(final QName rpcQName, final MessageCounter counter) {
468 final Document document = XmlUtil.newDocument();
469 final Element rpcNS =
470 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
472 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
473 final Element elementNS = document.createElementNS(rpcQName.getNamespace().toString(), rpcQName.getLocalName());
474 rpcNS.appendChild(elementNS);
475 document.appendChild(rpcNS);
476 return new DOMResult(elementNS);
479 public static DOMResult prepareDomResultForActionRequest(final DataSchemaContextTree dataSchemaContextTree,
480 final DOMDataTreeIdentifier domDataTreeIdentifier, final MessageCounter counter, final QName action) {
481 final Document document = XmlUtil.newDocument();
482 final Element rpcNS =
483 document.createElementNS(NETCONF_RPC_QNAME.getNamespace().toString(), NETCONF_RPC_QNAME.getLocalName());
485 rpcNS.setAttribute(MESSAGE_ID_ATTR, counter.getNewMessageId(MESSAGE_ID_PREFIX));
487 final Element actionNS = document.createElementNS(NETCONF_ACTION_NAMESPACE.toString(), NETCONF_ACTION);
488 final DataSchemaContextNode<?> rootSchemaContextNode = dataSchemaContextTree.getRoot();
489 final Element actionData = prepareActionData(rootSchemaContextNode, actionNS,
490 domDataTreeIdentifier.getRootIdentifier().getPathArguments().iterator(), document);
492 final Element specificActionElement =
493 document.createElementNS(action.getNamespace().toString(), action.getLocalName());
494 actionData.appendChild(specificActionElement);
495 rpcNS.appendChild(actionNS);
496 document.appendChild(rpcNS);
497 return new DOMResult(specificActionElement);
500 private static Element prepareActionData(final DataSchemaContextNode<?> currentParentSchemaNode,
501 final Element actionNS, final Iterator<PathArgument> iterator, final Document document) {
502 if (iterator.hasNext()) {
503 final PathArgument next = iterator.next();
505 final DataSchemaContextNode<?> current = currentParentSchemaNode.getChild(next);
506 Preconditions.checkArgument(current != null, "Invalid input: schema for argument %s not found", next);
508 if (current.isMixin()) {
509 return prepareActionData(current, actionNS, iterator, document);
512 final QName actualNS = next.getNodeType();
513 final Element actualElement = document.createElementNS(actualNS.getNamespace().toString(),
514 actualNS.getLocalName());
515 if (next instanceof NodeWithValue) {
516 actualElement.setNodeValue(((NodeWithValue<?>) next).getValue().toString());
517 } else if (next instanceof NodeIdentifierWithPredicates) {
518 for (Entry<QName, Object> entry : ((NodeIdentifierWithPredicates) next).entrySet()) {
519 final Element entryElement = document.createElementNS(entry.getKey().getNamespace().toString(),
520 entry.getKey().getLocalName());
521 entryElement.setTextContent(entry.getValue().toString());
522 entryElement.setNodeValue(entry.getValue().toString());
523 actualElement.appendChild(entryElement);
526 actionNS.appendChild(actualElement);
527 return prepareActionData(current, actualElement, iterator, document);
533 @SuppressWarnings("checkstyle:IllegalCatch")
534 public static void writeNormalizedOperationInput(final ContainerNode normalized, final DOMResult result,
535 final Absolute operationPath, final EffectiveModelContext baseNetconfCtx)
536 throws IOException, XMLStreamException {
537 final QName inputQName = YangConstants.operationInputQName(operationPath.lastNodeIdentifier().getModule());
538 // FIXME: eliminate this conversion
539 final SchemaPath inputPath = operationPath.asSchemaPath().createChild(inputQName);
541 final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
543 try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
544 XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, inputPath)) {
545 try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
546 new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, inputPath)) {
547 final Collection<DataContainerChild> value = normalized.body();
548 normalizedNodeWriter.write(value);
549 normalizedNodeWriter.flush();
555 } catch (final Exception e) {
556 LOG.warn("Unable to close resource properly", e);
561 public static RpcResult<NetconfMessage> toRpcResult(final FailedNetconfMessage message) {
562 return RpcResultBuilder.<NetconfMessage>failed()
563 .withRpcError(toRpcError(new NetconfDocumentedException(message.getException().getMessage(),
564 DocumentedException.ErrorType.APPLICATION,
565 DocumentedException.ErrorTag.MALFORMED_MESSAGE,
566 ErrorSeverity.ERROR)))