Add netconf.api.CapabilityURN
[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.NetconfMessage;
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;
30
31 /**
32  * Special kind of netconf message that contains a timestamp.
33  */
34 public final class NotificationMessage extends NetconfMessage {
35     private static final Logger LOG = LoggerFactory.getLogger(NotificationMessage.class);
36
37     /**
38      * Used for unknown/un-parse-able event-times.
39      */
40     // FIXME: we should differentiate unknown and invalid event times
41     public static final Instant UNKNOWN_EVENT_TIME = Instant.EPOCH;
42
43     /**
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]'.
47      */
48     private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;
49
50     /**
51      * Provide a {@link String} representation of a {@link Instant} object,
52      * using the time-zone offset for UTC, {@code ZoneOffset.UTC}.
53      */
54     public static final Function<Instant, String> RFC3339_DATE_FORMATTER = date ->
55             DATE_TIME_FORMATTER.format(date.atOffset(ZoneOffset.UTC));
56
57     /**
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()}.
61      * <p>
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
66      *     caller.
67      * </p>
68      */
69     public static final Function<String, Instant> RFC3339_DATE_PARSER = time -> {
70         try {
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;
76
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
79             if (reminder != 0) {
80                 final StringBuilder reminderBuilder = new StringBuilder(String.valueOf(reminder));
81
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');
85                 }
86
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);
90                 }
91                 LOG.warn("Fraction of second is cut to three digits. Value that was cut {}",
92                         reminderBuilder.toString());
93             }
94
95             return Instant.from(localDateTime);
96         } catch (DateTimeParseException exception) {
97             final var res = handlePotentialLeapSecond(time);
98             if (res != null) {
99                 return res;
100             }
101             throw exception;
102         }
103     };
104
105     /**
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.
109      *
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.
113      */
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));
118         // Bail fast
119         if (parsed == null) {
120             return null;
121         }
122
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);
126
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) {
131             return null;
132         }
133
134         LOG.trace("Received time contains leap second, adjusting by replacing the second-of-minute of 60 with 59 {}",
135                 time);
136
137         // Applying simple conversion replacing the second-of-minute of 60 with 59.
138
139         secondOfMinute = 59;
140
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);
146
147         final LocalDateTime currentTime = LocalDateTime.of(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour,
148                 secondOfMinute, nanoOfSecond);
149         final OffsetDateTime dateTimeWithZoneOffset = currentTime.atOffset(ZoneOffset.ofTotalSeconds(offsetSeconds));
150
151         return RFC3339_DATE_PARSER.apply(dateTimeWithZoneOffset.toString());
152     }
153
154     /**
155      * Get value asociated with {@code ChronoField}.
156      *
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,
160      *     else 0.
161      */
162     private static int getFieldFromTemporalAccessor(final TemporalAccessor accessor, final ChronoField field) {
163         return accessor.isSupported(field) ? (int) accessor.getLong(field) : 0;
164     }
165
166     private final @NonNull Instant eventTime;
167
168     /**
169      * Create new notification and capture the timestamp in the constructor.
170      */
171     public NotificationMessage(final Document notificationContent) {
172         this(notificationContent, Instant.now());
173     }
174
175     /**
176      * Create new notification with provided timestamp.
177      */
178     public NotificationMessage(final Document notificationContent, final Instant eventTime) {
179         super(wrapNotification(notificationContent, eventTime));
180         this.eventTime = requireNonNull(eventTime);
181     }
182
183     /**
184      * Get the time of the event.
185      *
186      * @return notification event time
187      */
188     public @NonNull Instant getEventTime() {
189         return eventTime;
190     }
191
192     private static Document wrapNotification(final Document notificationContent, final Instant eventTime) {
193         requireNonNull(notificationContent);
194         requireNonNull(eventTime);
195
196         final Element baseNotification = notificationContent.getDocumentElement();
197         final Element entireNotification = notificationContent.createElementNS(
198             XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_NOTIFICATION_1_0,
199             XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME);
200         entireNotification.appendChild(baseNotification);
201
202         final Element eventTimeElement = notificationContent.createElementNS(
203             XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_NOTIFICATION_1_0, 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 }