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.server.mdsal.streams.notif;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.gson.stream.JsonWriter;
12 import java.io.IOException;
13 import java.io.StringWriter;
14 import java.time.Instant;
15 import javax.xml.xpath.XPathExpressionException;
16 import org.eclipse.jdt.annotation.NonNull;
17 import org.opendaylight.mdsal.dom.api.DOMNotification;
18 import org.opendaylight.restconf.server.spi.TextParameters;
19 import org.opendaylight.yang.svc.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.YangModuleInfoImpl;
20 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
21 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
22 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
24 final class JSONNotificationFormatter extends NotificationFormatter {
25 private static final @NonNull String NOTIFICATION_NAME =
26 YangModuleInfoImpl.getInstance().getName().getLocalName() + ":notification";
28 static final JSONNotificationFormatter EMPTY = new JSONNotificationFormatter(TextParameters.EMPTY);
30 static final NotificationFormatterFactory FACTORY = new NotificationFormatterFactory(EMPTY) {
32 public JSONNotificationFormatter getFormatter(final TextParameters textParams, final String xpathFilter)
33 throws XPathExpressionException {
34 return new JSONNotificationFormatter(textParams, xpathFilter);
38 public JSONNotificationFormatter newFormatter(final TextParameters textParams) {
39 return new JSONNotificationFormatter(textParams);
43 private JSONNotificationFormatter(final TextParameters textParams) {
47 private JSONNotificationFormatter(final TextParameters textParams, final String xpathFilter)
48 throws XPathExpressionException {
49 super(textParams, xpathFilter);
53 protected String createText(final TextParameters params, final EffectiveModelContext schemaContext,
54 final DOMNotification input, final Instant now) throws IOException {
55 try (var writer = new StringWriter()) {
56 try (var jsonWriter = new JsonWriter(writer)) {
57 jsonWriter.beginObject()
58 .name(NOTIFICATION_NAME).beginObject()
59 .name("event-time").value(toRFC3339(now));
60 writeBody(JSONNormalizedNodeStreamWriter.createNestedWriter(
61 JSONCodecFactorySupplier.RFC7951.getShared(schemaContext), input.getType(), null, jsonWriter),
63 jsonWriter.endObject().endObject();
65 return writer.toString();