Add netconf.api.NamespaceURN
[netconf.git] / protocol / netconf-api / src / main / java / org / opendaylight / netconf / api / messages / NotificationMessage.java
1 /*
2  * Copyright (c) 2015 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.netconf.api.messages;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.text.ParsePosition;
13 import java.time.Instant;
14 import java.time.LocalDateTime;
15 import java.time.OffsetDateTime;
16 import java.time.ZoneOffset;
17 import java.time.ZonedDateTime;
18 import java.time.format.DateTimeFormatter;
19 import java.time.format.DateTimeParseException;
20 import java.time.temporal.ChronoField;
21 import java.time.temporal.TemporalAccessor;
22 import java.util.function.Function;
23 import org.eclipse.jdt.annotation.NonNull;
24 import org.opendaylight.netconf.api.NamespaceURN;
25 import org.opendaylight.netconf.api.NetconfMessage;
26 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.w3c.dom.Document;
30 import org.w3c.dom.Element;
31
32 /**
33  * Special kind of netconf message that contains a timestamp.
34  */
35 public final class NotificationMessage extends NetconfMessage {
36     private static final Logger LOG = LoggerFactory.getLogger(NotificationMessage.class);
37
38     /**
39      * Used for unknown/un-parse-able event-times.
40      */
41     // FIXME: we should differentiate unknown and invalid event times
42     public static final Instant UNKNOWN_EVENT_TIME = Instant.EPOCH;
43
44     /**
45      * The ISO-like date-time formatter that formats or parses a date-time with
46      * the offset and zone if available, such as '2011-12-03T10:15:30',
47      * '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
48      */
49     private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;
50
51     /**
52      * Provide a {@link String} representation of a {@link Instant} object,
53      * using the time-zone offset for UTC, {@code ZoneOffset.UTC}.
54      */
55     public static final Function<Instant, String> RFC3339_DATE_FORMATTER = date ->
56             DATE_TIME_FORMATTER.format(date.atOffset(ZoneOffset.UTC));
57
58     /**
59      * Parse a {@link String} object into a {@link Instant} using the time-zone
60      * offset for UTC, {@code ZoneOffset.UTC}, and the system default time-zone,
61      * {@code ZoneId.systemDefault()}.
62      * <p>
63      *     While parsing, if an exception occurs, we try to handle it as if it is due
64      *     to a leap second. If that's the case, a simple conversion is applied, replacing
65      *     the second-of-minute of 60 with 59.
66      *     If that's not the case, we propagate the {@link DateTimeParseException} to the
67      *     caller.
68      * </p>
69      */
70     public static final Function<String, Instant> RFC3339_DATE_PARSER = time -> {
71         try {
72             final ZonedDateTime localDateTime = ZonedDateTime.parse(time, DATE_TIME_FORMATTER);
73             final int startAt = 0;
74             final TemporalAccessor parsed = DATE_TIME_FORMATTER.parse(time, new ParsePosition(startAt));
75             final int nanoOfSecond = getFieldFromTemporalAccessor(parsed, ChronoField.NANO_OF_SECOND);
76             final long reminder = nanoOfSecond % 1000000;
77
78             // Log warn in case we rounded the fraction of a second. We need to create a string from the
79             // value that was cut. Example -> 1.123750 -> Value that was cut 75
80             if (reminder != 0) {
81                 final StringBuilder reminderBuilder = new StringBuilder(String.valueOf(reminder));
82
83                 //add zeros in case we have number like 123056 to make sure 056 is displayed
84                 while (reminderBuilder.length() < 6) {
85                     reminderBuilder.insert(0, '0');
86                 }
87
88                 //delete zeros from end to make sure that number like 1.123750 will show value cut 75.
89                 while (reminderBuilder.charAt(reminderBuilder.length() - 1) == '0') {
90                     reminderBuilder.deleteCharAt(reminderBuilder.length() - 1);
91                 }
92                 LOG.warn("Fraction of second is cut to three digits. Value that was cut {}",
93                         reminderBuilder.toString());
94             }
95
96             return Instant.from(localDateTime);
97         } catch (DateTimeParseException exception) {
98             final var res = handlePotentialLeapSecond(time);
99             if (res != null) {
100                 return res;
101             }
102             throw exception;
103         }
104     };
105
106     /**
107      * Check whether the input {@link String} is representing a time compliant with the ISO
108      * format and having a leap second; e.g. formatted as 23:59:60. If that's the case, a simple
109      * conversion is applied, replacing the second-of-minute of 60 with 59.
110      *
111      * @param time {@link String} representation of a time
112      * @return {@code null} if time isn't ISO compliant or if the time doesn't have a leap second else an
113      *         {@link Instant} as per as the RFC3339_DATE_PARSER.
114      */
115     private static Instant handlePotentialLeapSecond(final String time) {
116         // Parse the string from offset 0, so we get the whole value.
117         final int offset = 0;
118         final TemporalAccessor parsed = DATE_TIME_FORMATTER.parseUnresolved(time, new ParsePosition(offset));
119         // Bail fast
120         if (parsed == null) {
121             return null;
122         }
123
124         int secondOfMinute = getFieldFromTemporalAccessor(parsed, ChronoField.SECOND_OF_MINUTE);
125         final int hourOfDay = getFieldFromTemporalAccessor(parsed, ChronoField.HOUR_OF_DAY);
126         final int minuteOfHour = getFieldFromTemporalAccessor(parsed, ChronoField.MINUTE_OF_HOUR);
127
128         // Check whether the input time has leap second. As the leap second can only
129         // occur at 23:59:60, we can be very strict, and don't interpret an incorrect
130         // value as leap second.
131         if (secondOfMinute != 60 || minuteOfHour != 59 || hourOfDay != 23) {
132             return null;
133         }
134
135         LOG.trace("Received time contains leap second, adjusting by replacing the second-of-minute of 60 with 59 {}",
136                 time);
137
138         // Applying simple conversion replacing the second-of-minute of 60 with 59.
139
140         secondOfMinute = 59;
141
142         final int year = getFieldFromTemporalAccessor(parsed, ChronoField.YEAR);
143         final int monthOfYear = getFieldFromTemporalAccessor(parsed, ChronoField.MONTH_OF_YEAR);
144         final int dayOfMonth = getFieldFromTemporalAccessor(parsed, ChronoField.DAY_OF_MONTH);
145         final int nanoOfSecond = getFieldFromTemporalAccessor(parsed, ChronoField.NANO_OF_SECOND);
146         final int offsetSeconds = getFieldFromTemporalAccessor(parsed, ChronoField.OFFSET_SECONDS);
147
148         final LocalDateTime currentTime = LocalDateTime.of(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour,
149                 secondOfMinute, nanoOfSecond);
150         final OffsetDateTime dateTimeWithZoneOffset = currentTime.atOffset(ZoneOffset.ofTotalSeconds(offsetSeconds));
151
152         return RFC3339_DATE_PARSER.apply(dateTimeWithZoneOffset.toString());
153     }
154
155     /**
156      * Get value asociated with {@code ChronoField}.
157      *
158      * @param accessor The {@link TemporalAccessor}
159      * @param field The {@link ChronoField} to get
160      * @return the value associated with the {@link ChronoField} for the given {@link TemporalAccessor} if present,
161      *     else 0.
162      */
163     private static int getFieldFromTemporalAccessor(final TemporalAccessor accessor, final ChronoField field) {
164         return accessor.isSupported(field) ? (int) accessor.getLong(field) : 0;
165     }
166
167     private final @NonNull Instant eventTime;
168
169     /**
170      * Create new notification and capture the timestamp in the constructor.
171      */
172     public NotificationMessage(final Document notificationContent) {
173         this(notificationContent, Instant.now());
174     }
175
176     /**
177      * Create new notification with provided timestamp.
178      */
179     public NotificationMessage(final Document notificationContent, final Instant eventTime) {
180         super(wrapNotification(notificationContent, eventTime));
181         this.eventTime = requireNonNull(eventTime);
182     }
183
184     /**
185      * Get the time of the event.
186      *
187      * @return notification event time
188      */
189     public @NonNull Instant getEventTime() {
190         return eventTime;
191     }
192
193     private static Document wrapNotification(final Document notificationContent, final Instant eventTime) {
194         requireNonNull(notificationContent);
195         requireNonNull(eventTime);
196
197         final Element baseNotification = notificationContent.getDocumentElement();
198         final Element entireNotification = notificationContent.createElementNS(
199             NamespaceURN.NOTIFICATION, XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME);
200         entireNotification.appendChild(baseNotification);
201
202         final Element eventTimeElement = notificationContent.createElementNS(
203             NamespaceURN.NOTIFICATION, XmlNetconfConstants.EVENT_TIME);
204         eventTimeElement.setTextContent(RFC3339_DATE_FORMATTER.apply(eventTime));
205         entireNotification.appendChild(eventTimeElement);
206
207         notificationContent.appendChild(entireNotification);
208         return notificationContent;
209     }
210 }