2 * Copyright (c) 2013 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.client;
10 import com.google.common.collect.Collections2;
11 import java.util.Collection;
12 import java.util.List;
13 import java.util.Optional;
14 import org.opendaylight.netconf.api.DocumentedException;
15 import org.opendaylight.netconf.api.messages.NetconfMessage;
16 import org.opendaylight.netconf.api.xml.XmlElement;
17 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20 import org.w3c.dom.Document;
22 public final class NetconfMessageUtil {
23 private static final Logger LOG = LoggerFactory.getLogger(NetconfMessageUtil.class);
25 private NetconfMessageUtil() {
29 public static boolean isOKMessage(final NetconfMessage message) {
30 return isOKMessage(message.getDocument());
33 public static boolean isOKMessage(final Document document) {
34 return isOKMessage(XmlElement.fromDomDocument(document));
37 public static boolean isOKMessage(final XmlElement xmlElement) {
38 final var children = xmlElement.getChildElements();
39 return children.size() == 1 && children.get(0).getName().equals(XmlNetconfConstants.OK);
42 public static boolean isErrorMessage(final NetconfMessage message) {
43 return isErrorMessage(message.getDocument());
46 public static boolean isErrorMessage(final Document document) {
47 return isErrorMessage(XmlElement.fromDomDocument(document));
50 public static boolean isErrorMessage(final XmlElement xmlElement) {
51 // In the case of multiple rpc-error messages, size will not be 1 but we still want to report as Error
52 return xmlElement.getChildElements().stream()
53 .anyMatch(result -> DocumentedException.RPC_ERROR.equals(result.getName()));
56 public static Collection<String> extractCapabilitiesFromHello(final Document doc) {
57 XmlElement responseElement = XmlElement.fromDomDocument(doc);
58 // Extract child element <capabilities> from <hello> with or without(fallback) the same namespace
59 Optional<XmlElement> capabilitiesElement = responseElement
60 .getOnlyChildElementWithSameNamespaceOptionally(XmlNetconfConstants.CAPABILITIES);
61 if (capabilitiesElement.isEmpty()) {
62 capabilitiesElement = responseElement.getOnlyChildElementOptionally(XmlNetconfConstants.CAPABILITIES);
65 List<XmlElement> caps = capabilitiesElement.orElseThrow().getChildElements(XmlNetconfConstants.CAPABILITY);
66 return Collections2.transform(caps, input -> {
67 // Trim possible leading/tailing whitespace
69 return input.getTextContent().trim();
70 } catch (DocumentedException e) {
71 LOG.trace("Error fetching input text content",e);