1e4d1361a76b457e787cef384502adb4a9f7db0a
[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         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
224
225         if (writer != null) {
226             LOG.debug("{}: Writing subtree: {} in: {}", this, id, writer);
227             writer.update(id, null, dataAfter, ctx);
228         } else {
229             // If there's no dedicated writer, use write current
230             // But we need current data after to do so
231             final InstanceIdentifier<D> currentId = RWUtils.cutId(id, getManagedDataObjectType());
232             Optional<DataObject> currentDataAfter = ctx.readAfter(currentId);
233             LOG.debug("{}: Dedicated subtree writer missing for: {}. Writing current.", this,
234                 RWUtils.getNextId(id, getManagedDataObjectType()).getType(), currentDataAfter);
235             writeCurrent(currentId, castToManaged(currentDataAfter.get()), ctx);
236         }
237     }
238
239     private boolean idPointsToCurrent(final @Nonnull InstanceIdentifier<? extends DataObject> id) {
240         return id.getTargetType().equals(getManagedDataObjectType().getTargetType());
241     }
242
243     private void deleteSubtree(final InstanceIdentifier<? extends DataObject> id,
244                                final DataObject dataBefore, final WriteContext ctx) throws WriteFailedException {
245         LOG.debug("{}: Deleting subtree: {}", this, id);
246         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
247
248         if (writer != null) {
249             LOG.debug("{}: Deleting subtree: {} in: {}", this, id, writer);
250             writer.update(id, dataBefore, null, ctx);
251         } else {
252             updateSubtreeFromCurrent(id, ctx);
253         }
254     }
255
256     @SuppressWarnings("unchecked")
257     private void updateSubtreeFromCurrent(final InstanceIdentifier<? extends DataObject> id, final WriteContext ctx)
258         throws WriteFailedException {
259         final InstanceIdentifier<D> currentId = RWUtils.cutId(id, getManagedDataObjectType());
260         Optional<DataObject> currentDataBefore = ctx.readBefore(currentId);
261         Optional<DataObject> currentDataAfter = ctx.readAfter(currentId);
262         LOG.debug("{}: Dedicated subtree writer missing for: {}. Updating current without subtree", this,
263             RWUtils.getNextId(id, getManagedDataObjectType()).getType(), currentDataAfter);
264         updateCurrent((InstanceIdentifier<D>) id, castToManaged(currentDataBefore.orNull()),
265             castToManaged(currentDataAfter.orNull()), ctx);
266     }
267
268     private void updateSubtree(final InstanceIdentifier<? extends DataObject> id,
269                                final DataObject dataBefore,
270                                final DataObject dataAfter,
271                                final WriteContext ctx) throws WriteFailedException {
272         LOG.debug("{}: Updating subtree: {}", this, id);
273         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
274
275         if (writer != null) {
276             LOG.debug("{}: Updating subtree: {} in: {}", this, id, writer);
277             writer.update(id, dataBefore, dataAfter, ctx);
278         } else {
279             updateSubtreeFromCurrent(id, ctx);
280         }
281     }
282
283     private Writer<? extends ChildOf<D>> getNextWriter(final InstanceIdentifier<? extends DataObject> id) {
284         final Class<? extends DataObject> next = RWUtils.getNextId(id, getManagedDataObjectType()).getType();
285         return childWriters.get(next);
286     }
287
288     private static <T> List<T> reverseCollection(final Collection<T> original) {
289         // TODO find a better reverse mechanism (probably a different collection for child writers is necessary)
290         final ArrayList<T> list = Lists.newArrayList(original);
291         Collections.reverse(list);
292         return list;
293     }
294
295     protected abstract void writeCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
296                                                    @Nonnull final D data,
297                                                    @Nonnull final WriteContext ctx) throws WriteFailedException;
298
299     protected abstract void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
300                                                     @Nonnull final D dataBefore,
301                                                     @Nonnull final WriteContext ctx) throws WriteFailedException;
302
303     protected abstract void updateCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
304                                                     @Nonnull final D dataBefore,
305                                                     @Nonnull final D dataAfter,
306                                                     @Nonnull final WriteContext ctx) throws WriteFailedException;
307
308     @Nonnull
309     @Override
310     public InstanceIdentifier<D> getManagedDataObjectType() {
311         return instanceIdentifier;
312     }
313
314
315     @Override
316     public String toString() {
317         return String.format("Writer[%s]", getManagedDataObjectType().getTargetType().getSimpleName());
318     }
319 }