Add InstanceNotification(Publish)ServiceAdapter
[mdsal.git] / binding / mdsal-binding-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / dom / adapter / AbstractLazySerializedEvent.java
1 /*
2  * Copyright (c) 2022 PANTHEON.tech, s.r.o. 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.mdsal.binding.dom.adapter;
9
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import java.time.Instant;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
16 import org.opendaylight.mdsal.dom.api.DOMEvent;
17 import org.opendaylight.mdsal.dom.api.DOMNotification;
18 import org.opendaylight.yangtools.yang.binding.BaseNotification;
19 import org.opendaylight.yangtools.yang.binding.EventInstantAware;
20 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
21 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
22
23 /**
24  * Lazy serialized implementation of {@link DOMNotification} and {@link DOMEvent}.
25  *
26  * <p>
27  * This implementation performs serialization of data, only if receiver of notification actually accessed data from
28  * notification.
29  */
30 abstract class AbstractLazySerializedEvent<T extends BaseNotification> implements DOMNotification, DOMEvent {
31     private final @NonNull BindingNormalizedNodeSerializer codec;
32     private final @NonNull T data;
33     private final @NonNull Absolute type;
34     private final @NonNull Instant eventInstant;
35
36     private volatile ContainerNode domBody;
37
38     AbstractLazySerializedEvent(final BindingNormalizedNodeSerializer codec, final T data, final Absolute type) {
39         this.codec = requireNonNull(codec);
40         this.data = requireNonNull(data);
41         this.type = requireNonNull(type);
42         this.eventInstant = data instanceof EventInstantAware ? ((EventInstantAware) data).eventInstant()
43             : Instant.now();
44     }
45
46     @Override
47     public final Absolute getType() {
48         return type;
49     }
50
51     @Override
52     public final ContainerNode getBody() {
53         ContainerNode local = domBody;
54         if (local == null) {
55             domBody = local = verifyNotNull(loadBody(codec));
56         }
57         return local;
58     }
59
60     abstract @NonNull ContainerNode loadBody(@NonNull BindingNormalizedNodeSerializer codec);
61
62     @Override
63     public final Instant getEventInstant() {
64         return eventInstant;
65     }
66
67     final @NonNull T getBindingData() {
68         return data;
69     }
70 }