7e7bc1a0b8d56487a7bbdbd793288acb4ba42f60
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / streams / listeners / AbstractNotificationsData.java
1 /*
2  * Copyright (c) 2016 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.netconf.sal.streams.listeners;
9
10 import java.io.ByteArrayOutputStream;
11 import java.io.IOException;
12 import java.nio.charset.StandardCharsets;
13 import java.time.Instant;
14 import java.time.OffsetDateTime;
15 import java.time.ZoneId;
16 import java.time.format.DateTimeFormatter;
17 import javax.xml.stream.XMLOutputFactory;
18 import javax.xml.stream.XMLStreamException;
19 import javax.xml.stream.XMLStreamWriter;
20 import javax.xml.transform.OutputKeys;
21 import javax.xml.transform.Transformer;
22 import javax.xml.transform.TransformerException;
23 import javax.xml.transform.TransformerFactory;
24 import javax.xml.transform.dom.DOMResult;
25 import javax.xml.transform.dom.DOMSource;
26 import javax.xml.transform.stream.StreamResult;
27 import org.opendaylight.yangtools.util.xml.UntrustedXML;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
30 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
31 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
32 import org.opendaylight.yangtools.yang.model.util.SchemaInferenceStack.Inference;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.w3c.dom.Document;
36 import org.w3c.dom.Element;
37
38 /**
39  * Abstract class for processing and preparing data.
40  *
41  */
42 abstract class AbstractNotificationsData {
43     private static final Logger LOG = LoggerFactory.getLogger(AbstractNotificationsData.class);
44     private static final TransformerFactory TF = TransformerFactory.newInstance();
45     private static final XMLOutputFactory OF = XMLOutputFactory.newFactory();
46
47     /**
48      * Formats data specified by RFC3339.
49      *
50      * @param now time stamp
51      * @return Data specified by RFC3339.
52      */
53     protected static String toRFC3339(final Instant now) {
54         return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(OffsetDateTime.ofInstant(now, ZoneId.systemDefault()));
55     }
56
57     /**
58      * Creates {@link Document} document.
59      *
60      * @return {@link Document} document.
61      */
62     protected static Document createDocument() {
63         return UntrustedXML.newDocumentBuilder().newDocument();
64     }
65
66     /**
67      * Write normalized node to {@link DOMResult}.
68      *
69      * @param normalized
70      *            data
71      * @param inference
72      *            SchemaInferenceStack state for the data
73      * @return {@link DOMResult}
74      */
75     protected DOMResult writeNormalizedNode(final NormalizedNode normalized, final Inference inference)
76             throws IOException, XMLStreamException {
77         final Document doc = UntrustedXML.newDocumentBuilder().newDocument();
78         final DOMResult result = new DOMResult(doc);
79         NormalizedNodeWriter normalizedNodeWriter = null;
80         NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
81         XMLStreamWriter writer = null;
82
83         try {
84             writer = OF.createXMLStreamWriter(result);
85             normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, inference);
86             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
87
88             normalizedNodeWriter.write(normalized);
89
90             normalizedNodeWriter.flush();
91         } finally {
92             if (normalizedNodeWriter != null) {
93                 normalizedNodeWriter.close();
94             }
95             if (normalizedNodeStreamWriter != null) {
96                 normalizedNodeStreamWriter.close();
97             }
98             if (writer != null) {
99                 writer.close();
100             }
101         }
102
103         return result;
104     }
105
106     /**
107      * Generating base element of every notification.
108      *
109      * @param doc
110      *            base {@link Document}
111      * @return element of {@link Document}
112      */
113     protected Element basePartDoc(final Document doc) {
114         final Element notificationElement =
115                 doc.createElementNS("urn:ietf:params:xml:ns:netconf:notification:1.0", "notification");
116
117         doc.appendChild(notificationElement);
118
119         final Element eventTimeElement = doc.createElement("eventTime");
120         eventTimeElement.setTextContent(toRFC3339(Instant.now()));
121         notificationElement.appendChild(eventTimeElement);
122
123         return notificationElement;
124     }
125
126     /**
127      * Generating of {@link Document} transforming to string.
128      *
129      * @param doc
130      *            {@link Document} with data
131      * @return - string from {@link Document}
132      */
133     protected String transformDoc(final Document doc) {
134         final ByteArrayOutputStream out = new ByteArrayOutputStream();
135
136         try {
137             final Transformer transformer = TF.newTransformer();
138             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
139             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
140             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
141             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
142             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
143             transformer.transform(new DOMSource(doc), new StreamResult(out));
144         } catch (final TransformerException e) {
145             // FIXME: this should raise an exception
146             final String msg = "Error during transformation of Document into String";
147             LOG.error(msg, e);
148             return msg;
149         }
150
151         return new String(out.toByteArray(), StandardCharsets.UTF_8);
152     }
153 }