Expose streams with all supported encodings
[netconf.git] / restconf / restconf-nb / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / EventFormatter.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.io.IOException;
13 import java.io.Writer;
14 import java.time.Instant;
15 import java.time.OffsetDateTime;
16 import java.time.ZoneId;
17 import java.time.format.DateTimeFormatter;
18 import javax.xml.XMLConstants;
19 import javax.xml.parsers.DocumentBuilderFactory;
20 import javax.xml.parsers.ParserConfigurationException;
21 import javax.xml.stream.XMLOutputFactory;
22 import javax.xml.stream.XMLStreamException;
23 import javax.xml.stream.XMLStreamWriter;
24 import javax.xml.xpath.XPath;
25 import javax.xml.xpath.XPathConstants;
26 import javax.xml.xpath.XPathExpression;
27 import javax.xml.xpath.XPathExpressionException;
28 import javax.xml.xpath.XPathFactory;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.netconf.api.NamespaceURN;
32 import org.opendaylight.yangtools.concepts.Immutable;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
35 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
36 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
37 import org.w3c.dom.Document;
38 import org.w3c.dom.Element;
39
40 public abstract class EventFormatter<T> implements Immutable {
41     private static final XPathFactory XPF = XPathFactory.newInstance();
42
43     // FIXME: NETCONF-369: XPath operates without namespace context, therefore we need an namespace-unaware builder.
44     //        Once it is fixed we can use UntrustedXML instead.
45     private static final @NonNull DocumentBuilderFactory DBF;
46
47     static {
48         final DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
49         f.setCoalescing(true);
50         f.setExpandEntityReferences(false);
51         f.setIgnoringElementContentWhitespace(true);
52         f.setIgnoringComments(true);
53         f.setXIncludeAware(false);
54         try {
55             f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
56             f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
57             f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
58             f.setFeature("http://xml.org/sax/features/external-general-entities", false);
59             f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
60         } catch (final ParserConfigurationException e) {
61             throw new ExceptionInInitializerError(e);
62         }
63         DBF = f;
64     }
65
66     static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newFactory();
67
68     private final TextParameters textParams;
69     private final XPathExpression filter;
70
71     EventFormatter(final TextParameters textParams)  {
72         this.textParams = requireNonNull(textParams);
73         filter = null;
74     }
75
76     EventFormatter(final TextParameters params, final String xpathFilter) throws XPathExpressionException {
77         textParams = requireNonNull(params);
78
79         final XPath xpath;
80         synchronized (XPF) {
81             xpath = XPF.newXPath();
82         }
83         // FIXME: NETCONF-369: we need to bind the namespace context here and for that we need the SchemaContext
84         filter = xpath.compile(xpathFilter);
85     }
86
87     final @Nullable String eventData(final EffectiveModelContext schemaContext, final T input, final Instant now)
88             throws Exception {
89         return filterMatches(schemaContext, input, now) ? createText(textParams, schemaContext, input, now) : null;
90     }
91
92     /**
93      * Export the provided input into the provided document so we can verify whether a filter matches the content.
94      *
95      * @param doc the document to fill
96      * @param schemaContext context to use for the export
97      * @param input data to export
98      * @throws IOException if any IOException occurs during export to the document
99      */
100     abstract void fillDocument(Document doc, EffectiveModelContext schemaContext, T input) throws IOException;
101
102     /**
103      * Format the input data into string representation of the data provided.
104      *
105      * @param params output text parameters
106      * @param schemaContext context to use for the export
107      * @param input input data
108      * @param now time the event happened
109      * @return String representation of the formatted data
110      * @throws Exception if the underlying formatters fail to export the data to the requested format
111      */
112     abstract String createText(TextParameters params, EffectiveModelContext schemaContext, T input, Instant now)
113         throws Exception;
114
115     private boolean filterMatches(final EffectiveModelContext schemaContext, final T input, final Instant now)
116             throws IOException {
117         if (filter == null) {
118             return true;
119         }
120
121         final Document doc;
122         try {
123             doc = DBF.newDocumentBuilder().newDocument();
124         } catch (final ParserConfigurationException e) {
125             throw new IOException("Failed to create a new document", e);
126         }
127         fillDocument(doc, schemaContext, input);
128
129         final Boolean eval;
130         try {
131             eval = (Boolean) filter.evaluate(doc, XPathConstants.BOOLEAN);
132         } catch (final XPathExpressionException e) {
133             throw new IllegalStateException("Failed to evaluate expression " + filter, e);
134         }
135
136         return eval;
137     }
138
139     /**
140      * Formats data specified by RFC3339.
141      *
142      * @param now time stamp
143      * @return Data specified by RFC3339.
144      */
145     static final String toRFC3339(final Instant now) {
146         return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(OffsetDateTime.ofInstant(now, ZoneId.systemDefault()));
147     }
148
149     static final @NonNull Element createNotificationElement(final Document doc, final Instant now) {
150         final var notificationElement = doc.createElementNS(NamespaceURN.NOTIFICATION, "notification");
151         final var eventTimeElement = doc.createElement("eventTime");
152         eventTimeElement.setTextContent(toRFC3339(now));
153         notificationElement.appendChild(eventTimeElement);
154         return notificationElement;
155     }
156
157     static final @NonNull XMLStreamWriter createStreamWriterWithNotification(final Writer writer, final Instant now)
158             throws XMLStreamException {
159         final var xmlStreamWriter = XML_OUTPUT_FACTORY.createXMLStreamWriter(writer);
160         xmlStreamWriter.setDefaultNamespace(NamespaceURN.NOTIFICATION);
161
162         xmlStreamWriter.writeStartElement(NamespaceURN.NOTIFICATION, "notification");
163         xmlStreamWriter.writeDefaultNamespace(NamespaceURN.NOTIFICATION);
164
165         xmlStreamWriter.writeStartElement("eventTime");
166         xmlStreamWriter.writeCharacters(toRFC3339(now));
167         xmlStreamWriter.writeEndElement();
168         return xmlStreamWriter;
169     }
170
171     static final void writeBody(final NormalizedNodeStreamWriter writer, final NormalizedNode body) throws IOException {
172         try (var nodeWriter = NormalizedNodeWriter.forStreamWriter(writer)) {
173             nodeWriter.write(body);
174         }
175     }
176 }