Merge "Created Sample Feature Test Class for Base Feature Repository"
[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.Predicate;
11 import com.google.common.collect.Collections2;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.Iterables;
15 import com.google.common.collect.Sets;
16
17 import java.net.URI;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Map.Entry;
23
24 import javax.annotation.Nullable;
25
26 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.controller.netconf.api.NetconfMessage;
28 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
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.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.Node;
36 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
37 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
38 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
39 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
40 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
41 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.w3c.dom.Document;
45 import org.w3c.dom.Element;
46
47 public class NetconfMessageTransformUtil {
48
49     private NetconfMessageTransformUtil() {}
50
51     public static final QName IETF_NETCONF_MONITORING = QName.create("urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring", "2010-10-04", "ietf-netconf-monitoring");
52     public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
53     public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
54     public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
55     public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
56     public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
57     public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
58     static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, null, null));
59     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
60     public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
61     public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
62     public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
63     public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
64     public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
65     public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
66     public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
67     public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
68     public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
69     public static QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
70     public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
71     public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
72     public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
73     public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
74
75     public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
76             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
77     public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
78
79     public static URI NETCONF_CANDIDATE_URI = URI
80             .create("urn:ietf:params:netconf:capability:candidate:1.0");
81
82     // Discard changes message
83     public static final CompositeNode DISCARD_CHANGES_RPC_CONTENT =
84             NodeFactory.createImmutableCompositeNode(NETCONF_DISCARD_CHANGES_QNAME, null, Collections.<Node<?>>emptyList());
85
86     // Commit changes message
87     public static final CompositeNode COMMIT_RPC_CONTENT =
88             NodeFactory.createImmutableCompositeNode(NETCONF_COMMIT_QNAME, null, Collections.<Node<?>>emptyList());
89
90     public static Node<?> toFilterStructure(final YangInstanceIdentifier identifier) {
91         Node<?> previous = null;
92         if (Iterables.isEmpty(identifier.getPathArguments())) {
93             return null;
94         }
95
96         for (final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument component : identifier.getReversePathArguments()) {
97             if (component instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
98                 previous = toNode((YangInstanceIdentifier.NodeIdentifierWithPredicates)component, previous);
99             } else {
100                 previous = toNode(component, previous);
101             }
102         }
103         return filter("subtree", previous);
104     }
105
106     static Node<?> toNode(final YangInstanceIdentifier.NodeIdentifierWithPredicates argument, final Node<?> node) {
107         final List<Node<?>> list = new ArrayList<>();
108         for (final Map.Entry<QName, Object> arg : argument.getKeyValues().entrySet()) {
109             list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue()));
110         }
111         if (node != null) {
112             list.add(node);
113         }
114         return new CompositeNodeTOImpl(argument.getNodeType(), null, list);
115     }
116
117     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
118             throws NetconfDocumentedException {
119         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id");
120         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id");
121
122         if(inputMsgId.equals(outputMsgId) == false) {
123             Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
124                     .put( "actual-message-id", outputMsgId )
125                     .put( "expected-message-id", inputMsgId )
126                     .build();
127
128             throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
129                     null, NetconfDocumentedException.ErrorType.protocol,
130                     NetconfDocumentedException.ErrorTag.bad_attribute,
131                     NetconfDocumentedException.ErrorSeverity.error, errorInfo );
132         }
133     }
134
135     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
136         if(NetconfMessageUtil.isErrorMessage(output)) {
137             throw NetconfDocumentedException.fromXMLDocument( output.getDocument() );
138         }
139     }
140
141     public static RpcError toRpcError( final NetconfDocumentedException ex )
142     {
143         StringBuilder infoBuilder = new StringBuilder();
144         Map<String, String> errorInfo = ex.getErrorInfo();
145         if( errorInfo != null )
146         {
147             for( Entry<String,String> e: errorInfo.entrySet() ) {
148                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
149                 .append( "</" ).append( e.getKey() ).append( '>' );
150
151             }
152         }
153
154         ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
155         return severity == ErrorSeverity.ERROR ?
156                 RpcResultBuilder.newError(
157                         toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
158                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
159                             RpcResultBuilder.newWarning(
160                                     toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
161                                     ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
162     }
163
164     private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
165         switch( severity ) {
166         case warning:
167             return RpcError.ErrorSeverity.WARNING;
168         default:
169             return RpcError.ErrorSeverity.ERROR;
170         }
171     }
172
173     private static RpcError.ErrorType toRpcErrorType( final NetconfDocumentedException.ErrorType type )
174     {
175         switch( type ) {
176         case protocol:
177             return RpcError.ErrorType.PROTOCOL;
178         case rpc:
179             return RpcError.ErrorType.RPC;
180         case transport:
181             return RpcError.ErrorType.TRANSPORT;
182         default:
183             return RpcError.ErrorType.APPLICATION;
184         }
185     }
186
187     public static CompositeNode flattenInput(final CompositeNode node) {
188         final QName inputQName = QName.create(node.getNodeType(), "input");
189         final CompositeNode input = node.getFirstCompositeByName(inputQName);
190         if (input == null) {
191             return node;
192         }
193         if (input instanceof CompositeNode) {
194
195             final List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
196                     .addAll(input.getValue()) //
197                     .addAll(Collections2.filter(node.getValue(), new Predicate<Node<?>>() {
198                         @Override
199                         public boolean apply(@Nullable final Node<?> input) {
200                             return !inputQName.equals(input.getNodeType());
201                         }
202                     })) //
203                     .build();
204
205             return ImmutableCompositeNode.create(node.getNodeType(), nodes);
206         }
207
208         return input;
209     }
210
211     static Node<?> toNode(final YangInstanceIdentifier.PathArgument argument, final Node<?> node) {
212         if (node != null) {
213             return new CompositeNodeTOImpl(argument.getNodeType(), null, Collections.<Node<?>> singletonList(node));
214         } else {
215             return new SimpleNodeTOImpl<Void>(argument.getNodeType(), null, null);
216         }
217     }
218
219     public static Element getDataSubtree(final Document doc) {
220         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
221     }
222
223     public static boolean isDataRetrievalOperation(final QName rpc) {
224         return NETCONF_URI.equals(rpc.getNamespace())
225                 && (rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName()) || rpc.getLocalName().equals(
226                         NETCONF_GET_QNAME.getLocalName()));
227     }
228
229     public static boolean isDataEditOperation(final QName rpc) {
230         return NETCONF_URI.equals(rpc.getNamespace())
231                 && rpc.getLocalName().equals(NETCONF_EDIT_CONFIG_QNAME.getLocalName());
232     }
233
234     /**
235      * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
236      * <pre>
237      * {@code
238      * rpc
239      *   edit-config
240      *     config
241      *         // All schema nodes from remote schema
242      *     config
243      *   edit-config
244      * rpc
245      * }
246      * </pre>
247      *
248      * This makes the translation of rpc edit-config request(especially the config node)
249      * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
250      */
251     public static DataNodeContainer createSchemaForEdit(final SchemaContext schemaContext) {
252         final QName config = QName.create(NETCONF_EDIT_CONFIG_QNAME, "config");
253         final QName editConfig = QName.create(NETCONF_EDIT_CONFIG_QNAME, "edit-config");
254         final NodeContainerProxy configProxy = new NodeContainerProxy(config, schemaContext.getChildNodes());
255         final NodeContainerProxy editConfigProxy = new NodeContainerProxy(editConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
256         return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
257     }
258
259     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> node) {
260         if (node != null) {
261             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> singletonList(node));
262         } else {
263             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> emptyList());
264         }
265     }
266
267     public static CompositeNodeTOImpl wrap(final QName name, final Node<?> additional, final Node<?> node) {
268         if (node != null) {
269             return new CompositeNodeTOImpl(name, null, ImmutableList.of(additional, node));
270         } else {
271             return new CompositeNodeTOImpl(name, null, ImmutableList.<Node<?>> of(additional));
272         }
273     }
274
275     static ImmutableCompositeNode filter(final String type, final Node<?> node) {
276         final CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder(); //
277         it.setQName(NETCONF_FILTER_QNAME);
278         it.setAttribute(NETCONF_TYPE_QNAME, type);
279         if (node != null) {
280             return it.add(node).toInstance();
281         } else {
282             return it.toInstance();
283         }
284     }
285 }