Make constants really constant
[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.collect.ImmutableList;
13 import com.google.common.collect.ImmutableMap;
14 import java.io.IOException;
15 import java.net.URI;
16 import java.util.AbstractMap;
17 import java.util.Collections;
18 import java.util.Map;
19 import java.util.Map.Entry;
20 import javax.xml.stream.XMLOutputFactory;
21 import javax.xml.stream.XMLStreamException;
22 import javax.xml.stream.XMLStreamWriter;
23 import javax.xml.transform.dom.DOMResult;
24 import javax.xml.transform.dom.DOMSource;
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.controller.netconf.util.xml.XmlUtil;
29 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
30 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
32 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.RpcError;
35 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
36 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
37 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
40 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
41 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
42 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
45 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
46 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
47 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
48 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
49 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
52 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.w3c.dom.Document;
56 import org.w3c.dom.Element;
57
58 public class NetconfMessageTransformUtil {
59
60     private static final Logger LOG= LoggerFactory.getLogger(NetconfMessageTransformUtil.class);
61
62     public static final String MESSAGE_ID_ATTR = "message-id";
63     public static final XMLOutputFactory XML_FACTORY;
64
65     static {
66         XML_FACTORY = XMLOutputFactory.newFactory();
67         XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
68     }
69
70     public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.cachedReference(QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
71     private static final String SUBTREE = "subtree";
72
73     // Blank document used for creation of new DOM nodes
74     private static final Document BLANK_DOCUMENT = XmlUtil.newDocument();
75     public static final String EVENT_TIME = "eventTime";
76
77     private NetconfMessageTransformUtil() {}
78
79     public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring");
80     public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data");
81     public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema");
82     public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format");
83     public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location");
84     public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier");
85     public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version");
86     public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace");
87
88     public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications");
89
90     public static final QName NETCONF_QNAME = QName.cachedReference(QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf"));
91     public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
92
93     public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
94     public static final QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
95     public static final QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok");
96     public static final QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
97     public static final QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
98     public static final QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
99     public static final QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
100     public static final QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
101     public static final QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
102     public static final QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
103     public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate");
104     public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config");
105     public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
106     public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
107     public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
108     public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
109     public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
110     public static final QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
111     public static final QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
112     public static final QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
113     public static final QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
114
115     public static final URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
116             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
117     public static final String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
118
119     public static final URI NETCONF_CANDIDATE_URI = URI
120             .create("urn:ietf:params:netconf:capability:candidate:1.0");
121
122     public static final URI NETCONF_NOTIFICATONS_URI = URI
123             .create("urn:ietf:params:netconf:capability:notification:1.0");
124
125     public static final URI NETCONF_RUNNING_WRITABLE_URI = URI
126             .create("urn:ietf:params:netconf:capability:writable-running:1.0");
127
128     public static final QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock");
129     public static final QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock");
130
131     // Discard changes message
132     public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
133             Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
134
135     // Commit changes message
136     public static final ContainerNode COMMIT_RPC_CONTENT =
137             Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
138
139     // Get message
140     public static final ContainerNode GET_RPC_CONTENT =
141             Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_GET_QNAME)).build();
142
143     // Create-subscription changes message
144     public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
145             Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
146
147     public static final DataContainerChild<?, ?> EMPTY_FILTER;
148
149     static {
150         final NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
151         anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
152
153         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
154         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
155
156         anyXmlBuilder.withValue(new DOMSource(element));
157
158         EMPTY_FILTER = anyXmlBuilder.build();
159     }
160
161     public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
162         final NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
163         anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
164
165         final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
166
167         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
168         element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
169
170         try {
171             writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
172         } catch (IOException | XMLStreamException e) {
173             throw new IllegalStateException("Unable to serialize filter element for path " + identifier, e);
174         }
175         anyXmlBuilder.withValue(new DOMSource(element));
176
177         return anyXmlBuilder.build();
178     }
179
180     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
181             throws NetconfDocumentedException {
182         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
183         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
184
185         if(inputMsgId.equals(outputMsgId) == false) {
186             final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
187                     .put( "actual-message-id", outputMsgId )
188                     .put( "expected-message-id", inputMsgId )
189                     .build();
190
191             throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
192                     null, NetconfDocumentedException.ErrorType.protocol,
193                     NetconfDocumentedException.ErrorTag.bad_attribute,
194                     NetconfDocumentedException.ErrorSeverity.error, errorInfo );
195         }
196     }
197
198     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
199         if(NetconfMessageUtil.isErrorMessage(output)) {
200             throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
201         }
202     }
203
204     public static RpcError toRpcError( final NetconfDocumentedException ex ) {
205         final StringBuilder infoBuilder = new StringBuilder();
206         final Map<String, String> errorInfo = ex.getErrorInfo();
207         if(errorInfo != null) {
208             for( final Entry<String,String> e: errorInfo.entrySet() ) {
209                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
210                 .append( "</" ).append( e.getKey() ).append( '>' );
211
212             }
213         }
214
215         final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
216         return severity == ErrorSeverity.ERROR ?
217                 RpcResultBuilder.newError(
218                         toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
219                         ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
220                             RpcResultBuilder.newWarning(
221                                     toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
222                                     ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
223     }
224
225     private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
226         switch (severity) {
227         case warning:
228             return RpcError.ErrorSeverity.WARNING;
229         default:
230             return RpcError.ErrorSeverity.ERROR;
231         }
232     }
233
234     private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
235         switch (type) {
236         case protocol:
237             return RpcError.ErrorType.PROTOCOL;
238         case rpc:
239             return RpcError.ErrorType.RPC;
240         case transport:
241             return RpcError.ErrorType.TRANSPORT;
242         default:
243             return RpcError.ErrorType.APPLICATION;
244         }
245     }
246
247     public static YangInstanceIdentifier.NodeIdentifier toId(final YangInstanceIdentifier.PathArgument qname) {
248         return toId(qname.getNodeType());
249     }
250
251     public static YangInstanceIdentifier.NodeIdentifier toId(final QName nodeType) {
252         return new YangInstanceIdentifier.NodeIdentifier(nodeType);
253     }
254
255     public static Element getDataSubtree(final Document doc) {
256         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
257     }
258
259     public static boolean isDataRetrievalOperation(final QName rpc) {
260         return NETCONF_URI.equals(rpc.getNamespace())
261                 && (NETCONF_GET_CONFIG_QNAME.getLocalName().equals(rpc.getLocalName())
262                 || NETCONF_GET_QNAME.getLocalName().equals(rpc.getLocalName()));
263     }
264
265     public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
266         return new NodeContainerProxy(NETCONF_DATA_QNAME, schemaContext.getChildNodes());
267     }
268
269     public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
270         return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
271     }
272
273     public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
274         return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
275     }
276
277     public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
278                                                                      final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
279         final NormalizedNode<?, ?> configContent;
280
281         if (dataPath.isEmpty()) {
282             Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
283             Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
284                     "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
285             configContent = lastChildOverride.get();
286         } else {
287             final Entry<QName, ModifyAction> modifyOperation =
288                     operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
289             configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
290         }
291
292         final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
293         try {
294             writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
295         } catch (IOException | XMLStreamException e) {
296             throw new IllegalStateException("Unable to serialize edit config content element for path " + dataPath, e);
297         }
298         final DOMSource value = new DOMSource(element);
299
300         return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(
301                 Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build()).build();
302     }
303
304     public static SchemaPath toPath(final QName rpc) {
305         return SchemaPath.create(true, rpc);
306     }
307
308     // FIXME similar code is in netconf-notifications-impl , DRY
309     public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext context)
310             throws IOException, XMLStreamException {
311         NormalizedNodeWriter normalizedNodeWriter = null;
312         NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
313         XMLStreamWriter writer = null;
314         try {
315             writer = XML_FACTORY.createXMLStreamWriter(result);
316             normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
317             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
318
319             normalizedNodeWriter.write(normalized);
320
321             normalizedNodeWriter.flush();
322         } finally {
323             try {
324                 if(normalizedNodeWriter != null) {
325                     normalizedNodeWriter.close();
326                 }
327                 if(normalizedNodeStreamWriter != null) {
328                     normalizedNodeStreamWriter.close();
329                 }
330                 if(writer != null) {
331                     writer.close();
332                 }
333             } catch (final Exception e) {
334                 LOG.warn("Unable to close resource properly", e);
335             }
336         }
337     }
338 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.