Merge "Fix usage of StringBuilder when getting parent path in PathUtils Making consta...
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / util / NetconfMessageTransformUtil.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.util;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Predicate;
12 import com.google.common.collect.Collections2;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Sets;
17
18 import java.net.URI;
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
24
25 import javax.annotation.Nullable;
26
27 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.controller.netconf.api.NetconfMessage;
29 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.RpcError;
33 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
34 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
35 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.Node;
38 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
39 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
40 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
41 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
42 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
43 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.w3c.dom.Document;
48 import org.w3c.dom.Element;
49
50 public class NetconfMessageTransformUtil {
51
52     private NetconfMessageTransformUtil() {}
53
54     public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring");
55     public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format");
56     public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location");
57     public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier");
58     public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version");
59     public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace");
60
61     public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
62     public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
63     public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
64     public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
65     public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
66     public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
67     static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, null, null));
68     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
69     public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
70     public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
71     public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
72     public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
73     public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
74     public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
75     public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
76     public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
77     public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
78     public static QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
79     public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
80     public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
81     public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
82     public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
83
84     public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
85             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
86     public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
87
88     public static URI NETCONF_CANDIDATE_URI = URI
89             .create("urn:ietf:params:netconf:capability:candidate:1.0");
90
91     // Discard changes message
92     public static final CompositeNode DISCARD_CHANGES_RPC_CONTENT =
93             NodeFactory.createImmutableCompositeNode(NETCONF_DISCARD_CHANGES_QNAME, null, Collections.<Node<?>>emptyList());
94
95     // Commit changes message
96     public static final CompositeNode COMMIT_RPC_CONTENT =
97             NodeFactory.createImmutableCompositeNode(NETCONF_COMMIT_QNAME, null, Collections.<Node<?>>emptyList());
98
99     public static Node<?> toFilterStructure(final YangInstanceIdentifier identifier) {
100         Node<?> previous = null;
101         if (Iterables.isEmpty(identifier.getPathArguments())) {
102             return null;
103         }
104
105         for (final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument component : identifier.getReversePathArguments()) {
106             if (component instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
107                 previous = toNode((YangInstanceIdentifier.NodeIdentifierWithPredicates)component, previous);
108             } else {
109                 previous = toNode(component, previous);
110             }
111         }
112         return filter("subtree", previous);
113     }
114
115     static Node<?> toNode(final YangInstanceIdentifier.NodeIdentifierWithPredicates argument, final Node<?> node) {
116         final List<Node<?>> list = new ArrayList<>();
117         for (final Map.Entry<QName, Object> arg : argument.getKeyValues().entrySet()) {
118             list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue()));
119         }
120         if (node != null) {
121             list.add(node);
122         }
123         return new CompositeNodeTOImpl(argument.getNodeType(), null, list);
124     }
125
126     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
127             throws NetconfDocumentedException {
128         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id");
129         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id");
130
131         if(inputMsgId.equals(outputMsgId) == false) {
132             Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
133                     .put( "actual-message-id", outputMsgId )
134                     .put( "expected-message-id", inputMsgId )
135                     .build();
136
137             throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
138                     null, NetconfDocumentedException.ErrorType.protocol,
139                     NetconfDocumentedException.ErrorTag.bad_attribute,
140                     NetconfDocumentedException.ErrorSeverity.error, errorInfo );
141         }
142     }
143
144     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
145         if(NetconfMessageUtil.isErrorMessage(output)) {
146             throw NetconfDocumentedException.fromXMLDocument( output.getDocument() );
147         }
148     }
149
150     public static RpcError toRpcError( final NetconfDocumentedException ex )
151     {
152         StringBuilder infoBuilder = new StringBuilder();
153         Map<String, String> errorInfo = ex.getErrorInfo();
154         if( errorInfo != null )
155         {
156             for( Entry<String,String> e: errorInfo.entrySet() ) {
157                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
158                 .append( "</" ).append( e.getKey() ).append( '>' );
159
160             }
161         }
162
163         ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
164         return severity == ErrorSeverity.ERROR ?
165                 RpcResultBuilder.newError(
166                         toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
167                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
168                             RpcResultBuilder.newWarning(
169                                     toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
170                                     ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
171     }
172
173     private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
174         switch( severity ) {
175         case warning:
176             return RpcError.ErrorSeverity.WARNING;
177         default:
178             return RpcError.ErrorSeverity.ERROR;
179         }
180     }
181
182     private static RpcError.ErrorType toRpcErrorType( final NetconfDocumentedException.ErrorType type )
183     {
184         switch( type ) {
185         case protocol:
186             return RpcError.ErrorType.PROTOCOL;
187         case rpc:
188             return RpcError.ErrorType.RPC;
189         case transport:
190             return RpcError.ErrorType.TRANSPORT;
191         default:
192             return RpcError.ErrorType.APPLICATION;
193         }
194     }
195
196     public static CompositeNode flattenInput(final CompositeNode node) {
197         final QName inputQName = QName.create(node.getNodeType(), "input");
198         final CompositeNode input = node.getFirstCompositeByName(inputQName);
199         if (input == null) {
200             return node;
201         }
202         if (input instanceof CompositeNode) {
203
204             final List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
205                     .addAll(input.getValue()) //
206                     .addAll(Collections2.filter(node.getValue(), new Predicate<Node<?>>() {
207                         @Override
208                         public boolean apply(@Nullable final Node<?> input) {
209                             return !inputQName.equals(input.getNodeType());
210                         }
211                     })) //
212                     .build();
213
214             return ImmutableCompositeNode.create(node.getNodeType(), nodes);
215         }
216
217         return input;
218     }
219
220     static Node<?> toNode(final YangInstanceIdentifier.PathArgument argument, final Node<?> node) {
221         if (node != null) {
222             return new CompositeNodeTOImpl(argument.getNodeType(), null, Collections.<Node<?>> singletonList(node));
223         } else {
224             return new SimpleNodeTOImpl<Void>(argument.getNodeType(), null, null);
225         }
226     }
227
228     public static Element getDataSubtree(final Document doc) {
229         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
230     }
231
232     public static boolean isDataRetrievalOperation(final QName rpc) {
233         return NETCONF_URI.equals(rpc.getNamespace())
234                 && (rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName()) || rpc.getLocalName().equals(
235                         NETCONF_GET_QNAME.getLocalName()));
236     }
237
238     public static boolean isGetOperation(final QName rpc) {
239         return NETCONF_URI.equals(rpc.getNamespace()) && rpc.getLocalName().equals(NETCONF_GET_QNAME.getLocalName());
240     }
241
242     public static boolean isGetConfigOperation(final QName rpc) {
243         return NETCONF_URI.equals(rpc.getNamespace()) && rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName());
244     }
245
246     public static boolean isDataEditOperation(final QName rpc) {
247         return NETCONF_URI.equals(rpc.getNamespace())
248                 && rpc.getLocalName().equals(NETCONF_EDIT_CONFIG_QNAME.getLocalName());
249     }
250
251     /**
252      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
253      * <pre>
254      * {@code
255      * rpc
256      *   edit-config
257      *     config
258      *         // All schema nodes from remote schema
259      *     config
260      *   edit-config
261      * rpc
262      * }
263      * </pre>
264      *
265      * This makes the translation of rpc edit-config request(especially the config node)
266      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
267      */
268     public static DataNodeContainer createSchemaForEdit(final SchemaContext schemaContext) {
269         final QName config = QName.create(NETCONF_EDIT_CONFIG_QNAME, "config");
270         final QName editConfig = QName.create(NETCONF_EDIT_CONFIG_QNAME, "edit-config");
271         final NodeContainerProxy configProxy = new NodeContainerProxy(config, schemaContext.getChildNodes());
272         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(editConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
273         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
274     }
275
276     /**
277      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
278      * <pre>
279      * {@code
280      * rpc
281      *   get
282      *     filter
283      *         // All schema nodes from remote schema
284      *     filter
285      *   get
286      * rpc
287      * }
288      * </pre>
289      *
290      * This makes the translation of rpc get request(especially the config node)
291      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
292      */
293     public static DataNodeContainer createSchemaForGet(final SchemaContext schemaContext) {
294         final QName filter = QName.create(NETCONF_GET_QNAME, "filter");
295         final QName get = QName.create(NETCONF_GET_QNAME, "get");
296         final NodeContainerProxy configProxy = new NodeContainerProxy(filter, schemaContext.getChildNodes());
297         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(get, Sets.<DataSchemaNode>newHashSet(configProxy));
298         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
299     }
300
301     /**
302      * Creates artificial schema node for get rpc. This artificial schema looks like:
303      * <pre>
304      * {@code
305      * rpc
306      *   get-config
307      *     filter
308      *         // All schema nodes from remote schema
309      *     filter
310      *   get-config
311      * rpc
312      * }
313      * </pre>
314      *
315      * This makes the translation of rpc get-config request(especially the config node)
316      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
317      */
318     public static DataNodeContainer createSchemaForGetConfig(final SchemaContext schemaContext) {
319         final QName filter = QName.create(NETCONF_GET_CONFIG_QNAME, "filter");
320         final QName getConfig = QName.create(NETCONF_GET_CONFIG_QNAME, "get-config");
321         final NodeContainerProxy configProxy = new NodeContainerProxy(filter, schemaContext.getChildNodes());
322         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(getConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
323         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
324     }
325
326     /**
327      * Creates artificial schema node for schema defined rpc. This artificial schema looks like:
328      * <pre>
329      * {@code
330      * rpc
331      *   rpc-name
332      *      // All schema nodes from remote schema
333      *   rpc-name
334      * rpc
335      * }
336      * </pre>
337      *
338      * This makes the translation of schema defined rpc request
339      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
340      */
341     public static DataNodeContainer createSchemaForRpc(final QName rpcName, final SchemaContext schemaContext) {
342         Preconditions.checkNotNull(rpcName);
343         Preconditions.checkNotNull(schemaContext);
344
345         final NodeContainerProxy rpcBodyProxy = new NodeContainerProxy(rpcName, schemaContext.getChildNodes());
346         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(rpcBodyProxy));
347
348     }
349
350     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> node) {
351         if (node != null) {
352             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> singletonList(node));
353         } else {
354             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> emptyList());
355         }
356     }
357
358     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> additional, final Node<?> node) {
359         if (node != null) {
360             return new CompositeNodeTOImpl(name, null, ImmutableList.of(additional, node));
361         } else {
362             return new CompositeNodeTOImpl(name, null, ImmutableList.<Node<?>> of(additional));
363         }
364     }
365
366     static ImmutableCompositeNode filter(final String type, final Node<?> node) {
367         final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder(); //
368         it.setQName(NETCONF_FILTER_QNAME);
369         it.setAttribute(NETCONF_TYPE_QNAME, type);
370         if (node != null) {
371             return it.add(node).toInstance();
372         } else {
373             return it.toInstance();
374         }
375     }
376
377     public static Node<?> findNode(final CompositeNode node, final YangInstanceIdentifier identifier) {
378
379         Node<?> current = node;
380         for (final YangInstanceIdentifier.PathArgument arg : identifier.getPathArguments()) {
381             if (current instanceof SimpleNode<?>) {
382                 return null;
383             } else if (current instanceof CompositeNode) {
384                 final CompositeNode currentComposite = (CompositeNode) current;
385
386                 current = currentComposite.getFirstCompositeByName(arg.getNodeType());
387                 if (current == null) {
388                     current = currentComposite.getFirstCompositeByName(arg.getNodeType().withoutRevision());
389                 }
390                 if (current == null) {
391                     current = currentComposite.getFirstSimpleByName(arg.getNodeType());
392                 }
393                 if (current == null) {
394                     current = currentComposite.getFirstSimpleByName(arg.getNodeType().withoutRevision());
395                 }
396                 if (current == null) {
397                     return null;
398                 }
399             }
400         }
401         return current;
402     }
403 }