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