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;
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.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.restconf.rev170126.$YangModuleInfoImpl;
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 static final @NonNull String NOTIFICATION_NAME =
25 $YangModuleInfoImpl.getInstance().getName().getLocalName() + ":notification";
27 static final JSONNotificationFormatter EMPTY = new JSONNotificationFormatter(TextParameters.EMPTY);
29 static final NotificationFormatterFactory FACTORY = new NotificationFormatterFactory(EMPTY) {
31 public JSONNotificationFormatter getFormatter(final TextParameters textParams, final String xpathFilter)
32 throws XPathExpressionException {
33 return new JSONNotificationFormatter(textParams, xpathFilter);
37 public JSONNotificationFormatter newFormatter(final TextParameters textParams) {
38 return new JSONNotificationFormatter(textParams);
42 private JSONNotificationFormatter(final TextParameters textParams) {
46 private JSONNotificationFormatter(final TextParameters textParams, final String xpathFilter)
47 throws XPathExpressionException {
48 super(textParams, xpathFilter);
52 String createText(final TextParameters params, final EffectiveModelContext schemaContext,
53 final DOMNotification input, final Instant now) throws IOException {
54 try (var writer = new StringWriter()) {
55 try (var jsonWriter = new JsonWriter(writer)) {
56 jsonWriter.beginObject()
57 .name(NOTIFICATION_NAME).beginObject()
58 .name("event-time").value(toRFC3339(now));
59 writeBody(JSONNormalizedNodeStreamWriter.createNestedWriter(
60 JSONCodecFactorySupplier.RFC7951.getShared(schemaContext), input.getType(), null, jsonWriter),
62 jsonWriter.endObject().endObject();
64 return writer.toString();