Merge "BUG-770: NumberFormatException for input string on switch OFPT_HELLO"
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / NetconfMapping.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.sal.connect.netconf;
9
10 import java.net.URI;
11 import java.util.ArrayList;
12 import java.util.Collections;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Set;
16 import java.util.concurrent.atomic.AtomicInteger;
17
18 import javax.activation.UnsupportedDataTypeException;
19 import javax.annotation.Nullable;
20
21 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
22 import org.opendaylight.controller.netconf.api.NetconfMessage;
23 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
24 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
25 import org.opendaylight.controller.sal.common.util.Rpcs;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.RpcError;
28 import org.opendaylight.yangtools.yang.common.RpcResult;
29 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
32 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.Node;
34 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
35 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
36 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
37 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
38 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
39 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.w3c.dom.Document;
42 import org.w3c.dom.Element;
43
44 import com.google.common.base.Optional;
45 import com.google.common.base.Predicate;
46 import com.google.common.collect.Collections2;
47 import com.google.common.collect.ImmutableList;
48 import com.google.common.collect.Lists;
49
50 public class NetconfMapping {
51
52     public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
53     public static String NETCONF_MONITORING_URI = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring";
54     public static URI NETCONF_NOTIFICATION_URI = URI.create("urn:ietf:params:xml:ns:netconf:notification:1.0");
55     public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI.create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
56
57     public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
58     public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
59     public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
60     public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
61     public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
62     public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
63     public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
64     public static QName NETCONF_DELETE_CONFIG_QNAME = QName.create(NETCONF_QNAME, "delete-config");
65     public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
66     public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
67
68     public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
69     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
70     public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
71
72     public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
73     public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
74
75     public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
76     public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
77
78     public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
79     public static QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok");
80     public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
81     public static QName NETCONF_CREATE_SUBSCRIPTION_QNAME = QName.create(NETCONF_NOTIFICATION_URI, null,
82             "create-subscription");
83     public static QName NETCONF_CANCEL_SUBSCRIPTION_QNAME = QName.create(NETCONF_NOTIFICATION_URI, null,
84             "cancel-subscription");
85     public static QName IETF_NETCONF_MONITORING_MODULE = QName.create(NETCONF_MONITORING_URI, "2010-10-04",
86             "ietf-netconf-monitoring");
87
88     static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl(NETCONF_RUNNING_QNAME,
89             null, null));
90
91     public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
92
93     static AtomicInteger messageId = new AtomicInteger(0);
94
95     static Node<?> toFilterStructure(final InstanceIdentifier identifier) {
96         Node<?> previous = null;
97         if (identifier.getPath().isEmpty()) {
98             return null;
99         }
100
101         for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument component : Lists
102                 .reverse(identifier.getPath())) {
103             if (component instanceof NodeIdentifierWithPredicates) {
104                 previous = toNode((NodeIdentifierWithPredicates)component, previous);
105             } else {
106                 previous = toNode(component, previous);
107             }
108         }
109         return filter("subtree", previous);
110     }
111
112     static Node<?> toNode(final NodeIdentifierWithPredicates argument, final Node<?> node) {
113         List<Node<?>> list = new ArrayList<>();
114         for (Map.Entry<QName, Object> arg : argument.getKeyValues().entrySet()) {
115             list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue()));
116         }
117         if (node != null) {
118             list.add(node);
119         }
120         return new CompositeNodeTOImpl(argument.getNodeType(), null, list);
121     }
122
123     static Node<?> toNode(final PathArgument argument, final Node<?> node) {
124         if (node != null) {
125             return new CompositeNodeTOImpl(argument.getNodeType(), null, Collections.<Node<?>> singletonList(node));
126         } else {
127             return new SimpleNodeTOImpl(argument.getNodeType(), null, null);
128         }
129     }
130
131     static CompositeNode toCompositeNode(final NetconfMessage message, final Optional<SchemaContext> ctx) {
132         // TODO: implement general normalization to normalize incoming Netconf
133         // Message
134         // for Schema Context counterpart
135         return null;
136     }
137
138     static CompositeNode toNotificationNode(final NetconfMessage message, final Optional<SchemaContext> ctx) {
139         if (ctx.isPresent()) {
140             SchemaContext schemaContext = ctx.get();
141             Set<NotificationDefinition> notifications = schemaContext.getNotifications();
142             Document document = message.getDocument();
143             return XmlDocumentUtils.notificationToDomNodes(document, Optional.fromNullable(notifications), ctx.get());
144         }
145         return null;
146     }
147
148     static NetconfMessage toRpcMessage(final QName rpc, final CompositeNode node, final Optional<SchemaContext> ctx) {
149         CompositeNodeTOImpl rpcPayload = wrap(NETCONF_RPC_QNAME, flattenInput(node));
150         Document w3cPayload = null;
151         try {
152             w3cPayload = XmlDocumentUtils.toDocument(rpcPayload, XmlDocumentUtils.defaultValueCodecProvider());
153         } catch (UnsupportedDataTypeException e) {
154             throw new IllegalArgumentException("Unable to create message", e);
155         }
156         w3cPayload.getDocumentElement().setAttribute("message-id", "m-" + messageId.getAndIncrement());
157         return new NetconfMessage(w3cPayload);
158     }
159
160     static CompositeNode flattenInput(final CompositeNode node) {
161         final QName inputQName = QName.create(node.getNodeType(), "input");
162         CompositeNode input = node.getFirstCompositeByName(inputQName);
163         if (input == null)
164             return node;
165         if (input instanceof CompositeNode) {
166
167             List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
168                     .addAll(input.getValue()) //
169                     .addAll(Collections2.filter(node.getValue(), new Predicate<Node<?>>() {
170                         @Override
171                         public boolean apply(@Nullable final Node<?> input) {
172                             return input.getNodeType() != inputQName;
173                         }
174                     })) //
175                     .build();
176
177             return ImmutableCompositeNode.create(node.getNodeType(), nodes);
178         }
179
180         return input;
181     }
182
183     static RpcResult<CompositeNode> toRpcResult(final NetconfMessage message, final QName rpc, final Optional<SchemaContext> context) {
184         CompositeNode rawRpc;
185         if (context.isPresent())
186             if (isDataRetrieQNameReply(rpc)) {
187
188                 Element xmlData = getDataSubtree(message.getDocument());
189
190                 List<org.opendaylight.yangtools.yang.data.api.Node<?>> dataNodes = XmlDocumentUtils.toDomNodes(xmlData,
191                         Optional.of(context.get().getDataDefinitions()));
192
193                 CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder();
194                 it.setQName(NETCONF_RPC_REPLY_QNAME);
195                 it.add(ImmutableCompositeNode.create(NETCONF_DATA_QNAME, dataNodes));
196
197                 rawRpc = it.toInstance();
198                 // sys(xmlData)
199             } else {
200                 rawRpc = toCompositeNode(message, context);
201             }
202         else {
203             rawRpc = (CompositeNode) toCompositeNode(message.getDocument());
204         }
205         // rawRpc.
206         return Rpcs.getRpcResult(true, rawRpc, Collections.<RpcError> emptySet());
207     }
208
209     static Element getDataSubtree(final Document doc) {
210         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
211     }
212
213     static boolean isDataRetrieQNameReply(final QName it) {
214         return NETCONF_URI == it.getNamespace()
215                 && (it.getLocalName() == NETCONF_GET_CONFIG_QNAME.getLocalName() || it.getLocalName() == NETCONF_GET_QNAME
216                 .getLocalName());
217     }
218
219     static CompositeNodeTOImpl wrap(final QName name, final Node<?> node) {
220         if (node != null) {
221             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> singletonList(node));
222         } else {
223             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> emptyList());
224         }
225     }
226
227     static CompositeNodeTOImpl wrap(final QName name, final Node<?> additional, final Node<?> node) {
228         if (node != null) {
229             return new CompositeNodeTOImpl(name, null, ImmutableList.of(additional, node));
230         } else {
231             return new CompositeNodeTOImpl(name, null, ImmutableList.<Node<?>> of(additional));
232         }
233     }
234
235     static ImmutableCompositeNode filter(final String type, final Node<?> node) {
236         CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder(); //
237         it.setQName(NETCONF_FILTER_QNAME);
238         it.setAttribute(NETCONF_TYPE_QNAME, type);
239         if (node != null) {
240             return it.add(node).toInstance();
241         } else {
242             return it.toInstance();
243         }
244     }
245
246     public static Node<?> toCompositeNode(final Document document) {
247         return XmlDocumentUtils.toDomNode(document);
248     }
249
250     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output) {
251         String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id");
252         String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id");
253
254         if(inputMsgId.equals(outputMsgId) == false) {
255             String requestXml = XmlUtil.toString(input.getDocument());
256             String responseXml = XmlUtil.toString(output.getDocument());
257             throw new IllegalStateException(String.format("Rpc request and reply message IDs must be same. Request: %s, response: %s", requestXml, responseXml));
258         }
259     }
260
261     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
262         if(NetconfMessageUtil.isErrorMessage(output)) {
263             throw new IllegalStateException(String.format("Response contains error: %s", XmlUtil.toString(output.getDocument())));
264         }
265     }
266 }