0212c086b0601659bd2f4361adb5e750ecd9ab79
[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         if (dataBefore.equals(dataAfter)) {
102             LOG.debug("{}: Skipping current(no update): {}", this, id);
103             // No change, ignore
104             return;
105         }
106
107         switch (traversalType) {
108             case PREORDER: {
109                 LOG.trace("{}: Updating current attributes", this);
110                 updateCurrentAttributes(id, dataBefore, dataAfter, ctx);
111                 updateChildren(id, dataBefore, dataAfter, ctx);
112                 break;
113             }
114             case POSTORDER: {
115                 updateChildren(id, dataBefore, dataAfter, ctx);
116                 LOG.trace("{}: Updating current attributes", this);
117                 updateCurrentAttributes(id, dataBefore, dataAfter, ctx);
118                 break;
119             }
120         }
121
122         LOG.debug("{}: Current node updated successfully", this);
123     }
124
125     private void updateChildren(final InstanceIdentifier<D> id, final D dataBefore, final D dataAfter,
126                                 final WriteContext ctx) throws WriteFailedException {
127         for (ChildWriter<? extends ChildOf<D>> child : childWriters.values()) {
128             LOG.debug("{}: Updating child in: {}", this, child);
129             child.updateChild(id, dataBefore, dataAfter, ctx);
130         }
131
132         for (ChildWriter<? extends Augmentation<D>> child : augWriters.values()) {
133             LOG.debug("{}: Updating augment in: {}", this, child);
134             child.updateChild(id, dataBefore, dataAfter, ctx);
135         }
136     }
137
138     protected void deleteCurrent(final InstanceIdentifier<D> id, final D dataBefore, final WriteContext ctx)
139         throws WriteFailedException {
140         LOG.debug("{}: Deleting current: {} dataBefore: {}", this, id, dataBefore);
141
142         switch (traversalType) {
143             case PREORDER: {
144                 deleteChildren(id, dataBefore, ctx);
145                 LOG.trace("{}: Deleting current attributes", this);
146                 deleteCurrentAttributes(id, dataBefore, ctx);
147                 break;
148             }
149             case POSTORDER: {
150                 LOG.trace("{}: Deleting current attributes", this);
151                 deleteCurrentAttributes(id, dataBefore, ctx);
152                 deleteChildren(id, dataBefore, ctx);
153                 break;
154             }
155         }
156     }
157
158     private void deleteChildren(final InstanceIdentifier<D> id, final D dataBefore, final WriteContext ctx)
159         throws WriteFailedException {
160         for (ChildWriter<? extends Augmentation<D>> child : reverseCollection(augWriters.values())) {
161             LOG.debug("{}: Deleting augment in: {}", this, child);
162             child.deleteChild(id, dataBefore, ctx);
163         }
164
165         for (ChildWriter<? extends ChildOf<D>> child : reverseCollection(childWriters.values())) {
166             LOG.debug("{}: Deleting child in: {}", this, child);
167             child.deleteChild(id, dataBefore, ctx);
168         }
169     }
170
171     @SuppressWarnings("unchecked")
172     @Override
173     public void update(@Nonnull final InstanceIdentifier<? extends DataObject> id,
174                        @Nullable final DataObject dataBefore,
175                        @Nullable final DataObject dataAfter,
176                        @Nonnull final WriteContext ctx) throws WriteFailedException {
177         LOG.debug("{}: Updating : {}", this, id);
178         LOG.trace("{}: Updating : {}, from: {} to: {}", this, id, dataBefore, dataAfter);
179
180         if (idPointsToCurrent(id)) {
181             if(isWrite(dataBefore, dataAfter)) {
182                 writeCurrent((InstanceIdentifier<D>) id, castToManaged(dataAfter), ctx);
183             } else if(isDelete(dataBefore, dataAfter)) {
184                 deleteCurrent((InstanceIdentifier<D>) id, castToManaged(dataBefore), ctx);
185             } else {
186                 checkArgument(dataBefore != null && dataAfter != null, "No data to process");
187                 updateCurrent((InstanceIdentifier<D>) id, castToManaged(dataBefore), castToManaged(dataAfter), ctx);
188             }
189         } else {
190             if (isWrite(dataBefore, dataAfter)) {
191                 writeSubtree(id, dataAfter, ctx);
192             } else if (isDelete(dataBefore, dataAfter)) {
193                 deleteSubtree(id, dataBefore, ctx);
194             } else {
195                 checkArgument(dataBefore != null && dataAfter != null, "No data to process");
196                 updateSubtree(id, dataBefore, dataAfter, ctx);
197             }
198         }
199     }
200
201     private void checkDataType(final @Nullable DataObject dataAfter) {
202         checkArgument(getManagedDataObjectType().getTargetType().isAssignableFrom(dataAfter.getClass()));
203     }
204
205     private D castToManaged(final DataObject data) {
206         checkDataType(data);
207         return getManagedDataObjectType().getTargetType().cast(data);
208     }
209
210     private static boolean isWrite(final DataObject dataBefore,
211                                     final DataObject dataAfter) {
212         return dataBefore == null && dataAfter != null;
213     }
214
215     private static boolean isDelete(final DataObject dataBefore,
216                                     final DataObject dataAfter) {
217         return dataAfter == null && dataBefore != null;
218     }
219
220     private void writeSubtree(final InstanceIdentifier<? extends DataObject> id,
221                               final DataObject dataAfter, final WriteContext ctx) throws WriteFailedException {
222         LOG.debug("{}: Writing subtree: {}", this, id);
223
224         final Writer<? extends ChildOf<D>> writer = getNextChildWriter(id);
225         final Writer<? extends Augmentation<D>> augWriter = getNextAgumentationWriter(id);
226
227         if (writer != null) {
228             LOG.debug("{}: Writing subtree: {} in: {}", this, id, writer);
229             writer.update(id, null, dataAfter, ctx);
230         } else if (augWriter != null) {
231             LOG.debug("{}: Updating augmented subtree: {} in: {}", this, id, augWriter);
232             augWriter.update(id, null, dataAfter, ctx);
233         } else {
234             // If there's no dedicated writer, use write current
235             // But we need current data after to do so
236             final InstanceIdentifier<D> currentId = RWUtils.cutId(id, getManagedDataObjectType());
237             Optional<D> currentDataAfter = ctx.readAfter(currentId);
238             LOG.debug("{}: Dedicated subtree writer missing for: {}. Writing current.", this,
239                 RWUtils.getNextId(id, getManagedDataObjectType()).getType(), currentDataAfter);
240             writeCurrent(currentId, castToManaged(currentDataAfter.get()), ctx);
241         }
242     }
243
244     private boolean idPointsToCurrent(final @Nonnull InstanceIdentifier<? extends DataObject> id) {
245         return id.getTargetType().equals(getManagedDataObjectType().getTargetType());
246     }
247
248     private void deleteSubtree(final InstanceIdentifier<? extends DataObject> id,
249                                final DataObject dataBefore, final WriteContext ctx) throws WriteFailedException {
250         LOG.debug("{}: Deleting subtree: {}", this, id);
251
252         final Writer<? extends ChildOf<D>> writer = getNextChildWriter(id);
253         final Writer<? extends Augmentation<D>> augWriter = getNextAgumentationWriter(id);
254
255         if (writer != null) {
256             LOG.debug("{}: Deleting subtree: {} in: {}", this, id, writer);
257             writer.update(id, dataBefore, null, ctx);
258         } else if (augWriter != null) {
259             LOG.debug("{}: Updating augmented subtree: {} in: {}", this, id, augWriter);
260             augWriter.update(id, dataBefore, null, ctx);
261         }  else {
262             updateSubtreeFromCurrent(id, ctx);
263         }
264     }
265
266     @SuppressWarnings("unchecked")
267     private void updateSubtreeFromCurrent(final InstanceIdentifier<? extends DataObject> id, final WriteContext ctx)
268         throws WriteFailedException {
269         final InstanceIdentifier<D> currentId = RWUtils.cutId(id, getManagedDataObjectType());
270         Optional<D> currentDataBefore = ctx.readBefore(currentId);
271         Optional<D> currentDataAfter = ctx.readAfter(currentId);
272         LOG.debug("{}: Dedicated subtree writer missing for: {}. Updating current without subtree", this,
273             RWUtils.getNextId(id, getManagedDataObjectType()).getType(), currentDataAfter);
274         updateCurrent((InstanceIdentifier<D>) id, castToManaged(currentDataBefore.orNull()),
275             castToManaged(currentDataAfter.orNull()), ctx);
276     }
277
278     private void updateSubtree(final InstanceIdentifier<? extends DataObject> id,
279                                final DataObject dataBefore,
280                                final DataObject dataAfter,
281                                final WriteContext ctx) throws WriteFailedException {
282         LOG.debug("{}: Updating subtree: {}", this, id);
283         final Writer<? extends ChildOf<D>> writer = getNextChildWriter(id);
284         final Writer<? extends Augmentation<D>> augWriter = getNextAgumentationWriter(id);
285
286         if (writer != null) {
287             LOG.debug("{}: Updating subtree: {} in: {}", this, id, writer);
288             writer.update(id, dataBefore, dataAfter, ctx);
289         } else if (augWriter != null) {
290             LOG.debug("{}: Updating augmented subtree: {} in: {}", this, id, augWriter);
291             augWriter.update(id, dataBefore, dataAfter, ctx);
292         } else {
293             updateSubtreeFromCurrent(id, ctx);
294         }
295     }
296
297     private Writer<? extends ChildOf<D>> getNextChildWriter(final InstanceIdentifier<? extends DataObject> id) {
298         final Class<? extends DataObject> next = RWUtils.getNextId(id, getManagedDataObjectType()).getType();
299         return childWriters.get(next);
300     }
301
302     private Writer<? extends Augmentation<D>> getNextAgumentationWriter(final InstanceIdentifier<? extends DataObject> id) {
303         final Class<? extends DataObject> next = RWUtils.getNextId(id, getManagedDataObjectType()).getType();
304         return augWriters.get(next);
305     }
306
307     private static <T> List<T> reverseCollection(final Collection<T> original) {
308         // TODO find a better reverse mechanism (probably a different collection for child writers is necessary)
309         final ArrayList<T> list = Lists.newArrayList(original);
310         Collections.reverse(list);
311         return list;
312     }
313
314     protected abstract void writeCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
315                                                    @Nonnull final D data,
316                                                    @Nonnull final WriteContext ctx) throws WriteFailedException;
317
318     protected abstract void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
319                                                     @Nonnull final D dataBefore,
320                                                     @Nonnull final WriteContext ctx) throws WriteFailedException;
321
322     protected abstract void updateCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
323                                                     @Nonnull final D dataBefore,
324                                                     @Nonnull final D dataAfter,
325                                                     @Nonnull final WriteContext ctx) throws WriteFailedException;
326
327     @Nonnull
328     @Override
329     public InstanceIdentifier<D> getManagedDataObjectType() {
330         return instanceIdentifier;
331     }
332
333
334     @Override
335     public String toString() {
336         return String.format("Writer[%s]", getManagedDataObjectType().getTargetType().getSimpleName());
337     }
338 }