e971fbeff61572e47b26dbbb9df1e5e6aa9779fd
[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.TranslationException;
24 import io.fd.honeycomb.v3po.translate.write.ChildWriter;
25 import io.fd.honeycomb.v3po.translate.write.WriteContext;
26 import io.fd.honeycomb.v3po.translate.util.RWUtils;
27 import io.fd.honeycomb.v3po.translate.write.Writer;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.List;
32 import java.util.Map;
33 import javax.annotation.Nonnull;
34 import javax.annotation.Nullable;
35 import org.opendaylight.yangtools.yang.binding.Augmentation;
36 import org.opendaylight.yangtools.yang.binding.ChildOf;
37 import org.opendaylight.yangtools.yang.binding.DataObject;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public abstract class AbstractCompositeWriter<D extends DataObject> implements Writer<D> {
43
44     private static final Logger LOG = LoggerFactory.getLogger(AbstractCompositeWriter.class);
45
46     private final Map<Class<? extends DataObject>, ChildWriter<? extends ChildOf<D>>> childWriters;
47     private final Map<Class<? extends DataObject>, ChildWriter<? extends Augmentation<D>>> augWriters;
48     private final InstanceIdentifier<D> instanceIdentifier;
49
50     public AbstractCompositeWriter(final Class<D> type,
51                                    final List<ChildWriter<? extends ChildOf<D>>> childWriters,
52                                    final List<ChildWriter<? extends Augmentation<D>>> augWriters) {
53         this.instanceIdentifier = InstanceIdentifier.create(type);
54         this.childWriters = RWUtils.uniqueLinkedIndex(childWriters, RWUtils.MANAGER_CLASS_FUNCTION);
55         this.augWriters = RWUtils.uniqueLinkedIndex(augWriters, RWUtils.MANAGER_CLASS_AUG_FUNCTION);
56     }
57
58     protected void writeCurrent(final InstanceIdentifier<D> id, final D data, final WriteContext ctx) {
59         LOG.debug("{}: Writing current: {} data: {}", this, id, data);
60
61         LOG.trace("{}: Writing current attributes", this);
62         writeCurrentAttributes(id, data, ctx);
63
64         for (ChildWriter<? extends ChildOf<D>> child : childWriters.values()) {
65             LOG.debug("{}: Writing child in: {}", this, child);
66             child.writeChild(id, data, ctx);
67         }
68
69         for (ChildWriter<? extends Augmentation<D>> child : augWriters.values()) {
70             LOG.debug("{}: Writing augment in: {}", this, child);
71             child.writeChild(id, data, ctx);
72         }
73
74         LOG.debug("{}: Current node written successfully", this);
75     }
76
77     protected void updateCurrent(final InstanceIdentifier<D> id, final D dataBefore, final D dataAfter,
78                                  final WriteContext ctx) {
79         LOG.debug("{}: Updating current: {} dataBefore: {}, datAfter: {}", this, id, dataBefore, dataAfter);
80
81         if(dataBefore.equals(dataAfter)) {
82             LOG.debug("{}: Skipping current(no update): {}", this, id);
83             // No change, ignore
84             return;
85         }
86
87         LOG.trace("{}: Updating current attributes", this);
88         updateCurrentAttributes(id, dataBefore, dataAfter, ctx);
89
90         for (ChildWriter<? extends ChildOf<D>> child : childWriters.values()) {
91             LOG.debug("{}: Updating child in: {}", this, child);
92             child.updateChild(id, dataBefore, dataAfter, ctx);
93         }
94
95         for (ChildWriter<? extends Augmentation<D>> child : augWriters.values()) {
96             LOG.debug("{}: Updating augment in: {}", this, child);
97             child.updateChild(id, dataBefore, dataAfter, ctx);
98         }
99
100         LOG.debug("{}: Current node updated successfully", this);
101     }
102
103     protected void deleteCurrent(final InstanceIdentifier<D> id, final D dataBefore, final WriteContext ctx) {
104         LOG.debug("{}: Deleting current: {} dataBefore: {}", this, id, dataBefore);
105
106         // delete in reversed order
107         for (ChildWriter<? extends Augmentation<D>> child : reverseCollection(augWriters.values())) {
108             LOG.debug("{}: Deleting augment in: {}", this, child);
109             child.deleteChild(id, dataBefore, ctx);
110         }
111
112         for (ChildWriter<? extends ChildOf<D>> child : reverseCollection(childWriters.values())) {
113             LOG.debug("{}: Deleting child in: {}", this, child);
114             child.deleteChild(id, dataBefore, ctx);
115         }
116
117         LOG.trace("{}: Deleting current attributes", this);
118         deleteCurrentAttributes(id, dataBefore, ctx);
119     }
120
121     @SuppressWarnings("unchecked")
122     @Override
123     public void update(@Nonnull final InstanceIdentifier<? extends DataObject> id,
124                        @Nullable final DataObject dataBefore,
125                        @Nullable final DataObject dataAfter,
126                        @Nonnull final WriteContext ctx) throws TranslationException {
127         LOG.debug("{}: Updating : {}", this, id);
128         LOG.trace("{}: Updating : {}, from: {} to: {}", this, id, dataBefore, dataAfter);
129
130         if (idPointsToCurrent(id)) {
131             if(isWrite(dataBefore, dataAfter)) {
132                 writeCurrent((InstanceIdentifier<D>) id, castToManaged(dataAfter), ctx);
133             } else if(isDelete(dataBefore, dataAfter)) {
134                 deleteCurrent((InstanceIdentifier<D>) id, castToManaged(dataBefore), ctx);
135             } else {
136                 checkArgument(dataBefore != null && dataAfter != null, "No data to process");
137                 updateCurrent((InstanceIdentifier<D>) id, castToManaged(dataBefore), castToManaged(dataAfter), ctx);
138             }
139         } else {
140             if (isWrite(dataBefore, dataAfter)) {
141                 writeSubtree(id, dataAfter, ctx);
142             } else if (isDelete(dataBefore, dataAfter)) {
143                 deleteSubtree(id, dataBefore, ctx);
144             } else {
145                 checkArgument(dataBefore != null && dataAfter != null, "No data to process");
146                 updateSubtree(id, dataBefore, dataAfter, ctx);
147             }
148         }
149     }
150
151     private void checkDataType(final @Nullable DataObject dataAfter) {
152         checkArgument(getManagedDataObjectType().getTargetType().isAssignableFrom(dataAfter.getClass()));
153     }
154
155     private D castToManaged(final DataObject data) {
156         checkDataType(data);
157         return getManagedDataObjectType().getTargetType().cast(data);
158     }
159
160     private static boolean isWrite(final DataObject dataBefore,
161                                     final DataObject dataAfter) {
162         return dataBefore == null && dataAfter != null;
163     }
164
165     private static boolean isDelete(final DataObject dataBefore,
166                                     final DataObject dataAfter) {
167         return dataAfter == null && dataBefore != null;
168     }
169
170     private void writeSubtree(final InstanceIdentifier<? extends DataObject> id,
171                               final DataObject dataAfter, final WriteContext ctx) throws TranslationException {
172         LOG.debug("{}: Writing subtree: {}", this, id);
173         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
174
175         if (writer != null) {
176             LOG.debug("{}: Writing subtree: {} in: {}", this, id, writer);
177             writer.update(id, null, dataAfter, ctx);
178         } else {
179             // If there's no dedicated writer, use write current
180             // But we need current data after to do so
181             final InstanceIdentifier<D> currentId = RWUtils.cutId(id, getManagedDataObjectType());
182             Optional<DataObject> currentDataAfter = ctx.readAfter(currentId);
183             LOG.debug("{}: Dedicated subtree writer missing for: {}. Writing current.", this,
184                 RWUtils.getNextId(id, getManagedDataObjectType()).getType(), currentDataAfter);
185             writeCurrent(currentId, castToManaged(currentDataAfter.get()), ctx);
186         }
187     }
188
189     private boolean idPointsToCurrent(final @Nonnull InstanceIdentifier<? extends DataObject> id) {
190         return id.getTargetType().equals(getManagedDataObjectType().getTargetType());
191     }
192
193     @SuppressWarnings("unchecked")
194     private void deleteSubtree(final InstanceIdentifier<? extends DataObject> id,
195                                final DataObject dataBefore, final WriteContext ctx) throws TranslationException {
196         LOG.debug("{}: Deleting subtree: {}", this, id);
197         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
198
199         if (writer != null) {
200             LOG.debug("{}: Deleting subtree: {} in: {}", this, id, writer);
201             writer.update(id, dataBefore, null, ctx);
202         } else {
203             updateSubtreeFromCurrent(id, ctx);
204         }
205     }
206
207     @SuppressWarnings("unchecked")
208     private void updateSubtreeFromCurrent(final InstanceIdentifier<? extends DataObject> id, final WriteContext ctx) {
209         final InstanceIdentifier<D> currentId = RWUtils.cutId(id, getManagedDataObjectType());
210         Optional<DataObject> currentDataBefore = ctx.readBefore(currentId);
211         Optional<DataObject> currentDataAfter = ctx.readAfter(currentId);
212         LOG.debug("{}: Dedicated subtree writer missing for: {}. Updating current without subtree", this,
213             RWUtils.getNextId(id, getManagedDataObjectType()).getType(), currentDataAfter);
214         updateCurrent((InstanceIdentifier<D>) id, castToManaged(currentDataBefore.orNull()),
215             castToManaged(currentDataAfter.orNull()), ctx);
216     }
217
218     @SuppressWarnings("unchecked")
219     private void updateSubtree(final InstanceIdentifier<? extends DataObject> id,
220                                final DataObject dataBefore,
221                                final DataObject dataAfter,
222                                final WriteContext ctx) throws TranslationException {
223         LOG.debug("{}: Updating subtree: {}", this, id);
224         final Writer<? extends ChildOf<D>> writer = getNextWriter(id);
225
226         if (writer != null) {
227             LOG.debug("{}: Updating subtree: {} in: {}", this, id, writer);
228             writer.update(id, dataBefore, dataAfter, ctx);
229         } else {
230             updateSubtreeFromCurrent(id, ctx);
231         }
232     }
233
234     private Writer<? extends ChildOf<D>> getNextWriter(final InstanceIdentifier<? extends DataObject> id) {
235         final Class<? extends DataObject> next = RWUtils.getNextId(id, getManagedDataObjectType()).getType();
236         return childWriters.get(next);
237     }
238
239     private static <T> List<T> reverseCollection(final Collection<T> original) {
240         // TODO find a better reverse mechanism (probably a different collection for child writers is necessary)
241         final ArrayList<T> list = Lists.newArrayList(original);
242         Collections.reverse(list);
243         return list;
244     }
245
246     protected abstract void writeCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
247                                                    @Nonnull final D data,
248                                                    @Nonnull final WriteContext ctx);
249
250     protected abstract void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
251                                                     @Nonnull final D dataBefore,
252                                                     @Nonnull final WriteContext ctx);
253
254     protected abstract void updateCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
255                                                     @Nonnull final D dataBefore,
256                                                     @Nonnull final D dataAfter,
257                                                     @Nonnull final WriteContext ctx);
258
259     @Nonnull
260     @Override
261     public InstanceIdentifier<D> getManagedDataObjectType() {
262         return instanceIdentifier;
263     }
264
265
266     @Override
267     public String toString() {
268         return String.format("Writer[%s]", getManagedDataObjectType().getTargetType().getSimpleName());
269     }
270 }