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