2 * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.streams.listeners;
10 import static java.util.Objects.requireNonNull;
12 import com.google.gson.stream.JsonWriter;
13 import java.io.IOException;
14 import java.io.StringWriter;
15 import java.io.Writer;
16 import java.time.Instant;
17 import javax.xml.xpath.XPathExpressionException;
18 import org.opendaylight.mdsal.dom.api.DOMNotification;
19 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
20 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
21 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
23 final class JSONNotificationFormatter extends NotificationFormatter {
24 private final JSONCodecFactorySupplier codecSupplier;
26 private JSONNotificationFormatter(final JSONCodecFactorySupplier codecSupplier) {
27 this.codecSupplier = requireNonNull(codecSupplier);
30 private JSONNotificationFormatter(final String xpathFilter, final JSONCodecFactorySupplier codecSupplier)
31 throws XPathExpressionException {
33 this.codecSupplier = requireNonNull(codecSupplier);
36 static NotificationFormatterFactory createFactory(final JSONCodecFactorySupplier codecSupplier) {
37 requireNonNull(codecSupplier);
38 return new NotificationFormatterFactory() {
40 public JSONNotificationFormatter getFormatter(final String xpathFilter)
41 throws XPathExpressionException {
42 return new JSONNotificationFormatter(xpathFilter, codecSupplier);
46 public JSONNotificationFormatter getFormatter() {
47 return new JSONNotificationFormatter(codecSupplier);
53 String createText(final EffectiveModelContext schemaContext, final DOMNotification input, final Instant now,
54 final boolean leafNodesOnly, final boolean skipData, final boolean changedLeafNodesOnly,
55 final boolean childNodesOnly) throws IOException {
56 final Writer writer = new StringWriter();
57 final JsonWriter jsonWriter = new JsonWriter(writer).beginObject();
58 jsonWriter.name("ietf-restconf:notification").beginObject();
59 writeNotificationBody(JSONNormalizedNodeStreamWriter.createNestedWriter(
60 codecSupplier.getShared(schemaContext), input.getType(), null, jsonWriter), input.getBody());
61 jsonWriter.endObject();
62 jsonWriter.name("event-time").value(toRFC3339(now)).endObject();
64 return writer.toString();