Adopt odlparent-10.0.0/yangtools-8.0.0-SNAPSHOT
[mdsal.git] / replicate / mdsal-replicate-netty / src / main / java / org / opendaylight / mdsal / replicate / netty / AbstractSourceMessage.java
1 /*
2  * Copyright (c) 2020 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.replicate.netty;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.io.DataOutputStream;
13 import java.io.IOException;
14 import java.util.List;
15 import org.opendaylight.yangtools.yang.data.codec.binfmt.DataTreeCandidateInputOutput;
16 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataOutput;
17 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
18 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
19
20 abstract class AbstractSourceMessage {
21     private static final class Empty extends AbstractSourceMessage {
22         @Override
23         void encodeTo(final NormalizedNodeStreamVersion version, final List<Object> out) throws IOException {
24             out.add(Constants.EMPTY_DATA);
25         }
26     }
27
28     private static final class Deltas extends AbstractSourceMessage {
29         private final List<DataTreeCandidate> deltas;
30
31         Deltas(final List<DataTreeCandidate> deltas) {
32             this.deltas = requireNonNull(deltas);
33         }
34
35         @Override
36         void encodeTo(final NormalizedNodeStreamVersion version, final List<Object> out) throws IOException {
37             for (DataTreeCandidate candidate : deltas) {
38                 try (DataOutputStream stream = new DataOutputStream(new SplittingOutputStream(out))) {
39                     try (NormalizedNodeDataOutput output = version.newDataOutput(stream)) {
40                         DataTreeCandidateInputOutput.writeDataTreeCandidate(output, candidate);
41                     }
42                 }
43                 out.add(Constants.DTC_APPLY);
44             }
45         }
46     }
47
48     private static final AbstractSourceMessage EMPTY = new Empty();
49
50     static AbstractSourceMessage empty() {
51         return EMPTY;
52     }
53
54     static AbstractSourceMessage of(final List<DataTreeCandidate> deltas) {
55         return new Deltas(deltas);
56     }
57
58     abstract void encodeTo(NormalizedNodeStreamVersion version, List<Object> out) throws IOException;
59 }