da575164f9559def2a5fa6f27facfe491f685e7b
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / 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.restconf.nb.rfc8040.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.mdsal.common.api.LogicalDatastoreType;
28 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
29 import org.opendaylight.restconf.nb.rfc8040.Rfc8040.MonitoringModule;
30 import org.opendaylight.restconf.nb.rfc8040.handlers.SchemaContextHandler;
31 import org.opendaylight.restconf.nb.rfc8040.handlers.TransactionChainHandler;
32 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
33 import org.opendaylight.yangtools.util.xml.UntrustedXML;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
38 import org.opendaylight.yangtools.yang.data.codec.xml.XMLStreamNormalizedNodeStreamWriter;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.w3c.dom.Document;
44 import org.w3c.dom.Element;
45
46 /**
47  * Abstract class for processing and preparing data.
48  *
49  */
50 abstract class AbstractNotificationsData {
51     private static final Logger LOG = LoggerFactory.getLogger(AbstractNotificationsData.class);
52     private static final TransformerFactory TF = TransformerFactory.newInstance();
53     private static final XMLOutputFactory OF = XMLOutputFactory.newInstance();
54
55     private TransactionChainHandler transactionChainHandler;
56     protected SchemaContextHandler schemaHandler;
57     private String localName;
58
59     /**
60      * Transaction chain for delete data in DS on close().
61      *
62      * @param transactionChainHandler
63      *            creating new write transaction for delete data on close
64      * @param schemaHandler
65      *            for getting schema to deserialize
66      *            {@link MonitoringModule#PATH_TO_STREAM_WITHOUT_KEY} to
67      *            {@link YangInstanceIdentifier}
68      */
69     @SuppressWarnings("checkstyle:hiddenField")
70     public void setCloseVars(final TransactionChainHandler transactionChainHandler,
71             final SchemaContextHandler schemaHandler) {
72         this.transactionChainHandler = transactionChainHandler;
73         this.schemaHandler = schemaHandler;
74     }
75
76     /**
77      * Delete data in DS.
78      */
79     protected void deleteDataInDS() throws Exception {
80         final DOMDataTreeWriteTransaction wTx = this.transactionChainHandler.get().newWriteOnlyTransaction();
81         wTx.delete(LogicalDatastoreType.OPERATIONAL, IdentifierCodec
82                 .deserialize(MonitoringModule.PATH_TO_STREAM_WITHOUT_KEY + this.localName, this.schemaHandler.get()));
83         wTx.commit().get();
84     }
85
86     /**
87      * Set localName of last path element of specific listener.
88      *
89      * @param localName
90      *            local name
91      */
92     @SuppressWarnings("checkstyle:hiddenField")
93     protected void setLocalNameOfPath(final String localName) {
94         this.localName = localName;
95     }
96
97     /**
98      * Formats data specified by RFC3339.
99      *
100      * @param now time stamp
101      * @return Data specified by RFC3339.
102      */
103     protected static String toRFC3339(final Instant now) {
104         return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(OffsetDateTime.ofInstant(now, ZoneId.systemDefault()));
105     }
106
107     /**
108      * Creates {@link Document} document.
109      *
110      * @return {@link Document} document.
111      */
112     protected static Document createDocument() {
113         return UntrustedXML.newDocumentBuilder().newDocument();
114     }
115
116     /**
117      * Write normalized node to {@link DOMResult}.
118      *
119      * @param normalized
120      *            data
121      * @param context
122      *            actual schema context
123      * @param schemaPath
124      *            schema path of data
125      * @return {@link DOMResult}
126      */
127     protected DOMResult writeNormalizedNode(final NormalizedNode<?, ?> normalized, final SchemaContext context,
128             final SchemaPath schemaPath) throws IOException, XMLStreamException {
129         final Document doc = UntrustedXML.newDocumentBuilder().newDocument();
130         final DOMResult result = new DOMResult(doc);
131         NormalizedNodeWriter normalizedNodeWriter = null;
132         NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
133         XMLStreamWriter writer = null;
134
135         try {
136             writer = OF.createXMLStreamWriter(result);
137             normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
138             normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
139
140             normalizedNodeWriter.write(normalized);
141
142             normalizedNodeWriter.flush();
143         } finally {
144             if (normalizedNodeWriter != null) {
145                 normalizedNodeWriter.close();
146             }
147             if (normalizedNodeStreamWriter != null) {
148                 normalizedNodeStreamWriter.close();
149             }
150             if (writer != null) {
151                 writer.close();
152             }
153         }
154
155         return result;
156     }
157
158     /**
159      * Generating base element of every notification.
160      *
161      * @param doc
162      *            base {@link Document}
163      * @return element of {@link Document}
164      */
165     protected Element basePartDoc(final Document doc) {
166         final Element notificationElement =
167                 doc.createElementNS("urn:ietf:params:xml:ns:netconf:notification:1.0", "notification");
168
169         doc.appendChild(notificationElement);
170
171         final Element eventTimeElement = doc.createElement("eventTime");
172         eventTimeElement.setTextContent(toRFC3339(Instant.now()));
173         notificationElement.appendChild(eventTimeElement);
174
175         return notificationElement;
176     }
177
178     /**
179      * Generating of {@link Document} transforming to string.
180      *
181      * @param doc
182      *            {@link Document} with data
183      * @return - string from {@link Document}
184      */
185     protected String transformDoc(final Document doc) {
186         final ByteArrayOutputStream out = new ByteArrayOutputStream();
187
188         try {
189             final Transformer transformer = TF.newTransformer();
190             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
191             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
192             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
193             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
194             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
195             transformer.transform(new DOMSource(doc), new StreamResult(out));
196         } catch (final TransformerException e) {
197             // FIXME: this should raise an exception
198             final String msg = "Error during transformation of Document into String";
199             LOG.error(msg, e);
200             return msg;
201         }
202
203         return new String(out.toByteArray(), StandardCharsets.UTF_8);
204     }
205 }