8b42a6c6fa7cdd7bd426de9346fa1c7ee49923a2
[hc2vpp.git] /
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package io.fd.honeycomb.v3po.translate.impl.write;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20
21 import com.google.common.base.Optional;
22 import com.google.common.collect.Lists;
23 import io.fd.honeycomb.v3po.translate.impl.TraversalType;
24 import io.fd.honeycomb.v3po.translate.util.RWUtils;
25 import io.fd.honeycomb.v3po.translate.write.ChildWriter;
26 import io.fd.honeycomb.v3po.translate.write.WriteContext;
27 import io.fd.honeycomb.v3po.translate.write.WriteFailedException;
28 import io.fd.honeycomb.v3po.translate.write.Writer;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.Map;
34 import javax.annotation.Nonnull;
35 import javax.annotation.Nullable;
36 import org.opendaylight.yangtools.yang.binding.Augmentation;
37 import org.opendaylight.yangtools.yang.binding.ChildOf;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 public abstract class AbstractCompositeWriter<D extends DataObject> implements Writer<D> {
44
45     private static final Logger LOG = LoggerFactory.getLogger(AbstractCompositeWriter.class);
46
47     private final Map<Class<? extends DataObject>, ChildWriter<? extends ChildOf<D>>> childWriters;
48     private final Map<Class<? extends DataObject>, ChildWriter<? extends Augmentation<D>>> augWriters;
49     private final InstanceIdentifier<D> instanceIdentifier;
50     private TraversalType traversalType;
51
52     public AbstractCompositeWriter(final Class<D> type,
53                                    final List<ChildWriter<? extends ChildOf<D>>> childWriters,
54                                    final List<ChildWriter<? extends Augmentation<D>>> augWriters,
55                                    final TraversalType traversalType) {
56         this.traversalType = traversalType;
57         this.instanceIdentifier = InstanceIdentifier.create(type);
58         this.childWriters = RWUtils.uniqueLinkedIndex(childWriters, RWUtils.MANAGER_CLASS_FUNCTION);
59         this.augWriters = RWUtils.uniqueLinkedIndex(augWriters, RWUtils.MANAGER_CLASS_AUG_FUNCTION);
60     }
61
62     protected void writeCurrent(final InstanceIdentifier<D> id, final D data, final WriteContext ctx)
63         throws WriteFailedException {
64         LOG.debug("{}: Writing current: {} data: {}", this, id, data);
65
66         switch (traversalType) {
67             case PREORDER: {
68                 LOG.trace("{}: Writing current attributes", this);
69                 writeCurrentAttributes(id, data, ctx);
70                 writeChildren(id, data, ctx);
71                 break;
72             }
73             case POSTORDER: {
74                 writeChildren(id, data, ctx);
75                 LOG.trace("{}: Writing current attributes", this);
76                 writeCurrentAttributes(id, data, ctx);
77                 break;
78             }
79         }
80
81         LOG.debug("{}: Current node written successfully", this);
82     }
83
84     private void writeChildren(final InstanceIdentifier<D> id, final D data, final WriteContext ctx)
85         throws WriteFailedException {
86         for (ChildWriter<? extends ChildOf<D>> child : childWriters.values()) {
87             LOG.debug("{}: Writing child in: {}", this, child);
88             child.writeChild(id, data, ctx);
89         }
90
91         for (ChildWriter<? extends Augmentation<D>> child : augWriters.values()) {
92             LOG.debug("{}: Writing augment in: {}", this, child);
93             child.writeChild(id, data, ctx);
94         }
95     }
96
97     protected void updateCurrent(final InstanceIdentifier<D> id, final D dataBefore, final D dataAfter,
98                                  final WriteContext ctx) throws WriteFailedException {
99         LOG.debug("{}: Updating current: {} dataBefore: {}, datAfter: {}", this, id, dataBefore, dataAfter);
100
101         // FIXME: Equals does not work properly with augments: https://git.opendaylight.org/gerrit/#/c/37719
102         // Solution: update mdsal-binding-dom-codec to 0.8.2-Beryllium-SR2 when it will be published in
103         // ODL release repository
104         //if (dataBefore.equals(dataAfter)) {
105         //    LOG.debug("{}: Skipping current(no update): {}", this, id);
106         //    // No change, ignore
107         //    return;
108         //}
109
110         switch (traversalType) {
111             case PREORDER: {
112                 LOG.trace("{}: Updating current attributes", this);
113                 updateCurrentAttributes(id, dataBefore, dataAfter, ctx);
114                 updateChildren(id, dataBefore, dataAfter, ctx);
115                 break;
116             }
117             case POSTORDER: {
118                 updateChildren(id, dataBefore, dataAfter, ctx);
119                 LOG.trace("{}: Updating current attributes", this);
120                 updateCurrentAttributes(id, dataBefore, dataAfter, ctx);
121                 break;
122             }
123         }
124
125         LOG.debug("{}: Current node updated successfully", this);
126     }
127
128     private void updateChildren(final InstanceIdentifier<D> id, final D dataBefore, final D dataAfter,
129                                 final WriteContext ctx) throws WriteFailedException {
130         for (ChildWriter<? extends ChildOf<D>> child : childWriters.values()) {
131             LOG.debug("{}: Updating child in: {}", this, child);
132             child.updateChild(id, dataBefore, dataAfter, ctx);
133         }
134
135         for (ChildWriter<? extends Augmentation<D>> child : augWriters.values()) {
136             LOG.debug("{}: Updating augment in: {}", this, child);
137             child.updateChild(id, dataBefore, dataAfter, ctx);
138         }
139     }
140
141     protected void deleteCurrent(final InstanceIdentifier<D> id, final D dataBefore, final WriteContext ctx)
142         throws WriteFailedException {
143         LOG.debug("{}: Deleting current: {} dataBefore: {}", this, id, dataBefore);
144
145         switch (traversalType) {
146             case PREORDER: {
147                 deleteChildren(id, dataBefore, ctx);
148                 LOG.trace("{}: Deleting current attributes", this);
149                 deleteCurrentAttributes(id, dataBefore, ctx);
150                 break;
151             }
152             case POSTORDER: {
153                 LOG.trace("{}: Deleting current attributes", this);
154                 deleteCurrentAttributes(id, dataBefore, ctx);
155                 deleteChildren(id, dataBefore, ctx);
156                 break;
157             }
158         }
159     }
160
161     private void deleteChildren(final InstanceIdentifier<D> id, final D dataBefore, final WriteContext ctx)
162         throws WriteFailedException {
163         for (ChildWriter<? extends Augmentation<D>> child : reverseCollection(augWriters.values())) {
164             LOG.debug("{}: Deleting augment in: {}", this, child);
165             child.deleteChild(id, dataBefore, ctx);
166         }
167
168         for (ChildWriter<? extends ChildOf<D>> child : reverseCollection(childWriters.values())) {
169             LOG.debug("{}: Deleting child in: {}", this, child);
170             child.deleteChild(id, dataBefore, ctx);
171         }
172     }
173
174     @SuppressWarnings("unchecked")
175     @Override
176     public void update(@Nonnull final InstanceIdentifier<? extends DataObject> id,
177                        @Nullable final DataObject dataBefore,
178                        @Nullable final DataObject dataAfter,
179                        @Nonnull final WriteContext ctx) throws WriteFailedException {
180         LOG.debug("{}: Updating : {}", this, id);
181         LOG.trace("{}: Updating : {}, from: {} to: {}", this, id, dataBefore, dataAfter);
182
183         if (idPointsToCurrent(id)) {
184             if(isWrite(dataBefore, dataAfter)) {
185                 writeCurrent((InstanceIdentifier<D>) id, castToManaged(dataAfter), ctx);
186             } else if(isDelete(dataBefore, dataAfter)) {
187                 deleteCurrent((InstanceIdentifier<D>) id, castToManaged(dataBefore), ctx);
188             } else {
189                 checkArgument(dataBefore != null && dataAfter != null, "No data to process");
190                 updateCurrent((InstanceIdentifier<D>) id, castToManaged(dataBefore), castToManaged(dataAfter), ctx);
191             }
192         } else {
193             if (isWrite(dataBefore, dataAfter)) {
194                 writeSubtree(id, dataAfter, ctx);
195             } else if (isDelete(dataBefore, dataAfter)) {
196                 deleteSubtree(id, dataBefore, ctx);
197             } else {
198                 checkArgument(dataBefore != null && dataAfter != null, "No data to process");
199                 updateSubtree(id, dataBefore, dataAfter, ctx);
200             }
201         }
202     }
203
204     private void checkDataType(final @Nullable DataObject dataAfter) {
205         checkArgument(getManagedDataObjectType().getTargetType().isAssignableFrom(dataAfter.getClass()));
206     }
207
208     private D castToManaged(final DataObject data) {
209         checkDataType(data);
210         return getManagedDataObjectType().getTargetType().cast(data);
211     }
212
213     private static boolean isWrite(final DataObject dataBefore,
214                                     final DataObject dataAfter) {
215         return dataBefore == null && dataAfter != null;
216     }
217
218     private static boolean isDelete(final DataObject dataBefore,
219                                     final DataObject dataAfter) {
220         return dataAfter == null && dataBefore != null;
221     }
222
223     private void writeSubtree(final InstanceIdentifier<? extends DataObject> id,
224                               final DataObject dataAfter, final WriteContext ctx) throws WriteFailedException {
225         LOG.debug("{}: Writing subtree: {}", this, id);
226         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
227
228         if (writer != null) {
229             LOG.debug("{}: Writing subtree: {} in: {}", this, id, writer);
230             writer.update(id, null, dataAfter, ctx);
231         } else {
232             // If there's no dedicated writer, use write current
233             // But we need current data after to do so
234             final InstanceIdentifier<D> currentId = RWUtils.cutId(id, getManagedDataObjectType());
235             Optional<D> currentDataAfter = ctx.readAfter(currentId);
236             LOG.debug("{}: Dedicated subtree writer missing for: {}. Writing current.", this,
237                 RWUtils.getNextId(id, getManagedDataObjectType()).getType(), currentDataAfter);
238             writeCurrent(currentId, castToManaged(currentDataAfter.get()), ctx);
239         }
240     }
241
242     private boolean idPointsToCurrent(final @Nonnull InstanceIdentifier<? extends DataObject> id) {
243         return id.getTargetType().equals(getManagedDataObjectType().getTargetType());
244     }
245
246     private void deleteSubtree(final InstanceIdentifier<? extends DataObject> id,
247                                final DataObject dataBefore, final WriteContext ctx) throws WriteFailedException {
248         LOG.debug("{}: Deleting subtree: {}", this, id);
249         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
250
251         if (writer != null) {
252             LOG.debug("{}: Deleting subtree: {} in: {}", this, id, writer);
253             writer.update(id, dataBefore, null, ctx);
254         } else {
255             updateSubtreeFromCurrent(id, ctx);
256         }
257     }
258
259     @SuppressWarnings("unchecked")
260     private void updateSubtreeFromCurrent(final InstanceIdentifier<? extends DataObject> id, final WriteContext ctx)
261         throws WriteFailedException {
262         final InstanceIdentifier<D> currentId = RWUtils.cutId(id, getManagedDataObjectType());
263         Optional<D> currentDataBefore = ctx.readBefore(currentId);
264         Optional<D> currentDataAfter = ctx.readAfter(currentId);
265         LOG.debug("{}: Dedicated subtree writer missing for: {}. Updating current without subtree", this,
266             RWUtils.getNextId(id, getManagedDataObjectType()).getType(), currentDataAfter);
267         updateCurrent((InstanceIdentifier<D>) id, castToManaged(currentDataBefore.orNull()),
268             castToManaged(currentDataAfter.orNull()), ctx);
269     }
270
271     private void updateSubtree(final InstanceIdentifier<? extends DataObject> id,
272                                final DataObject dataBefore,
273                                final DataObject dataAfter,
274                                final WriteContext ctx) throws WriteFailedException {
275         LOG.debug("{}: Updating subtree: {}", this, id);
276         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
277
278         if (writer != null) {
279             LOG.debug("{}: Updating subtree: {} in: {}", this, id, writer);
280             writer.update(id, dataBefore, dataAfter, ctx);
281         } else {
282             updateSubtreeFromCurrent(id, ctx);
283         }
284     }
285
286     private Writer<? extends ChildOf<D>> getNextWriter(final InstanceIdentifier<? extends DataObject> id) {
287         final Class<? extends DataObject> next = RWUtils.getNextId(id, getManagedDataObjectType()).getType();
288         return childWriters.get(next);
289     }
290
291     private static <T> List<T> reverseCollection(final Collection<T> original) {
292         // TODO find a better reverse mechanism (probably a different collection for child writers is necessary)
293         final ArrayList<T> list = Lists.newArrayList(original);
294         Collections.reverse(list);
295         return list;
296     }
297
298     protected abstract void writeCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
299                                                    @Nonnull final D data,
300                                                    @Nonnull final WriteContext ctx) throws WriteFailedException;
301
302     protected abstract void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
303                                                     @Nonnull final D dataBefore,
304                                                     @Nonnull final WriteContext ctx) throws WriteFailedException;
305
306     protected abstract void updateCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
307                                                     @Nonnull final D dataBefore,
308                                                     @Nonnull final D dataAfter,
309                                                     @Nonnull final WriteContext ctx) throws WriteFailedException;
310
311     @Nonnull
312     @Override
313     public InstanceIdentifier<D> getManagedDataObjectType() {
314         return instanceIdentifier;
315     }
316
317
318     @Override
319     public String toString() {
320         return String.format("Writer[%s]", getManagedDataObjectType().getTargetType().getSimpleName());
321     }
322 }