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