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