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