2 * Copyright (c) 2015 Cisco Systems, Inc. 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.netconf.api.messages;
10 import static java.util.Objects.requireNonNull;
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.xml.XmlNetconfConstants;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28 import org.w3c.dom.Document;
29 import org.w3c.dom.Element;
32 * Special kind of netconf message that contains a timestamp.
34 public final class NotificationMessage extends NetconfMessage {
35 private static final Logger LOG = LoggerFactory.getLogger(NotificationMessage.class);
38 * Used for unknown/un-parse-able event-times.
40 // FIXME: we should differentiate unknown and invalid event times
41 public static final Instant UNKNOWN_EVENT_TIME = Instant.EPOCH;
44 * The ISO-like date-time formatter that formats or parses a date-time with
45 * the offset and zone if available, such as '2011-12-03T10:15:30',
46 * '2011-12-03T10:15:30+01:00' or '2011-12-03T10:15:30+01:00[Europe/Paris]'.
48 private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;
51 * Provide a {@link String} representation of a {@link Instant} object,
52 * using the time-zone offset for UTC, {@code ZoneOffset.UTC}.
54 public static final Function<Instant, String> RFC3339_DATE_FORMATTER = date ->
55 DATE_TIME_FORMATTER.format(date.atOffset(ZoneOffset.UTC));
58 * Parse a {@link String} object into a {@link Instant} using the time-zone
59 * offset for UTC, {@code ZoneOffset.UTC}, and the system default time-zone,
60 * {@code ZoneId.systemDefault()}.
62 * While parsing, if an exception occurs, we try to handle it as if it is due
63 * to a leap second. If that's the case, a simple conversion is applied, replacing
64 * the second-of-minute of 60 with 59.
65 * If that's not the case, we propagate the {@link DateTimeParseException} to the
69 public static final Function<String, Instant> RFC3339_DATE_PARSER = time -> {
71 final ZonedDateTime localDateTime = ZonedDateTime.parse(time, DATE_TIME_FORMATTER);
72 final int startAt = 0;
73 final TemporalAccessor parsed = DATE_TIME_FORMATTER.parse(time, new ParsePosition(startAt));
74 final int nanoOfSecond = getFieldFromTemporalAccessor(parsed, ChronoField.NANO_OF_SECOND);
75 final long reminder = nanoOfSecond % 1000000;
77 // Log warn in case we rounded the fraction of a second. We need to create a string from the
78 // value that was cut. Example -> 1.123750 -> Value that was cut 75
80 final StringBuilder reminderBuilder = new StringBuilder(String.valueOf(reminder));
82 //add zeros in case we have number like 123056 to make sure 056 is displayed
83 while (reminderBuilder.length() < 6) {
84 reminderBuilder.insert(0, '0');
87 //delete zeros from end to make sure that number like 1.123750 will show value cut 75.
88 while (reminderBuilder.charAt(reminderBuilder.length() - 1) == '0') {
89 reminderBuilder.deleteCharAt(reminderBuilder.length() - 1);
91 LOG.warn("Fraction of second is cut to three digits. Value that was cut {}",
92 reminderBuilder.toString());
95 return Instant.from(localDateTime);
96 } catch (DateTimeParseException exception) {
97 final var res = handlePotentialLeapSecond(time);
106 * Check whether the input {@link String} is representing a time compliant with the ISO
107 * format and having a leap second; e.g. formatted as 23:59:60. If that's the case, a simple
108 * conversion is applied, replacing the second-of-minute of 60 with 59.
110 * @param time {@link String} representation of a time
111 * @return {@code null} if time isn't ISO compliant or if the time doesn't have a leap second else an
112 * {@link Instant} as per as the RFC3339_DATE_PARSER.
114 private static Instant handlePotentialLeapSecond(final String time) {
115 // Parse the string from offset 0, so we get the whole value.
116 final int offset = 0;
117 final TemporalAccessor parsed = DATE_TIME_FORMATTER.parseUnresolved(time, new ParsePosition(offset));
119 if (parsed == null) {
123 int secondOfMinute = getFieldFromTemporalAccessor(parsed, ChronoField.SECOND_OF_MINUTE);
124 final int hourOfDay = getFieldFromTemporalAccessor(parsed, ChronoField.HOUR_OF_DAY);
125 final int minuteOfHour = getFieldFromTemporalAccessor(parsed, ChronoField.MINUTE_OF_HOUR);
127 // Check whether the input time has leap second. As the leap second can only
128 // occur at 23:59:60, we can be very strict, and don't interpret an incorrect
129 // value as leap second.
130 if (secondOfMinute != 60 || minuteOfHour != 59 || hourOfDay != 23) {
134 LOG.trace("Received time contains leap second, adjusting by replacing the second-of-minute of 60 with 59 {}",
137 // Applying simple conversion replacing the second-of-minute of 60 with 59.
141 final int year = getFieldFromTemporalAccessor(parsed, ChronoField.YEAR);
142 final int monthOfYear = getFieldFromTemporalAccessor(parsed, ChronoField.MONTH_OF_YEAR);
143 final int dayOfMonth = getFieldFromTemporalAccessor(parsed, ChronoField.DAY_OF_MONTH);
144 final int nanoOfSecond = getFieldFromTemporalAccessor(parsed, ChronoField.NANO_OF_SECOND);
145 final int offsetSeconds = getFieldFromTemporalAccessor(parsed, ChronoField.OFFSET_SECONDS);
147 final LocalDateTime currentTime = LocalDateTime.of(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour,
148 secondOfMinute, nanoOfSecond);
149 final OffsetDateTime dateTimeWithZoneOffset = currentTime.atOffset(ZoneOffset.ofTotalSeconds(offsetSeconds));
151 return RFC3339_DATE_PARSER.apply(dateTimeWithZoneOffset.toString());
155 * Get value asociated with {@code ChronoField}.
157 * @param accessor The {@link TemporalAccessor}
158 * @param field The {@link ChronoField} to get
159 * @return the value associated with the {@link ChronoField} for the given {@link TemporalAccessor} if present,
162 private static int getFieldFromTemporalAccessor(final TemporalAccessor accessor, final ChronoField field) {
163 return accessor.isSupported(field) ? (int) accessor.getLong(field) : 0;
166 private final @NonNull Instant eventTime;
169 * Create new notification and capture the timestamp in the constructor.
171 public NotificationMessage(final Document notificationContent) {
172 this(notificationContent, Instant.now());
176 * Create new notification with provided timestamp.
178 public NotificationMessage(final Document notificationContent, final Instant eventTime) {
179 super(wrapNotification(notificationContent, eventTime));
180 this.eventTime = requireNonNull(eventTime);
184 * Get the time of the event.
186 * @return notification event time
188 public @NonNull Instant getEventTime() {
192 private static Document wrapNotification(final Document notificationContent, final Instant eventTime) {
193 requireNonNull(notificationContent);
194 requireNonNull(eventTime);
196 final Element baseNotification = notificationContent.getDocumentElement();
197 final Element entireNotification = notificationContent.createElementNS(
198 NamespaceURN.NOTIFICATION, XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME);
199 entireNotification.appendChild(baseNotification);
201 final Element eventTimeElement = notificationContent.createElementNS(
202 NamespaceURN.NOTIFICATION, XmlNetconfConstants.EVENT_TIME);
203 eventTimeElement.setTextContent(RFC3339_DATE_FORMATTER.apply(eventTime));
204 entireNotification.appendChild(eventTimeElement);
206 notificationContent.appendChild(entireNotification);
207 return notificationContent;