HONEYCOMB-431: add validation support to Writers
[honeycomb.git] / infra / translate-utils / src / main / java / io / fd / honeycomb / translate / util / write / AbstractGenericWriter.java
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.translate.util.write;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20
21 import io.fd.honeycomb.translate.util.RWUtils;
22 import io.fd.honeycomb.translate.write.DataValidationFailedException;
23 import io.fd.honeycomb.translate.write.Validator;
24 import io.fd.honeycomb.translate.write.WriteContext;
25 import io.fd.honeycomb.translate.write.WriteFailedException;
26 import io.fd.honeycomb.translate.write.Writer;
27 import javax.annotation.Nonnull;
28 import javax.annotation.Nullable;
29 import org.opendaylight.yangtools.yang.binding.DataObject;
30 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 public abstract class AbstractGenericWriter<D extends DataObject> implements Writer<D> {
35
36     private static final Logger LOG = LoggerFactory.getLogger(AbstractGenericWriter.class);
37
38     private final InstanceIdentifier<D> instanceIdentifier;
39     private final boolean supportsUpdate;
40     private Validator<D> validator;
41
42     protected AbstractGenericWriter(final InstanceIdentifier<D> type, final boolean supportsUpdate) {
43         this.instanceIdentifier = RWUtils.makeIidWildcarded(type);
44         this.supportsUpdate = supportsUpdate;
45     }
46
47     protected AbstractGenericWriter(final InstanceIdentifier<D> type, final boolean supportsUpdate,
48                                     final Validator<D> validator) {
49         this(type, supportsUpdate);
50         this.validator = validator;
51     }
52
53     protected void writeCurrent(final InstanceIdentifier<D> id, final D data, final WriteContext ctx)
54         throws WriteFailedException {
55         LOG.debug("{}: Writing current: {} data: {}", this, id, data);
56         writeCurrentAttributes(id, data, ctx);
57         LOG.debug("{}: Current node written successfully", this);
58     }
59
60     protected void updateCurrent(final InstanceIdentifier<D> id, final D dataBefore, final D dataAfter,
61                                  final WriteContext ctx) throws WriteFailedException {
62         LOG.debug("{}: Updating current: {} dataBefore: {}, datAfter: {}", this, id, dataBefore, dataAfter);
63
64         if (dataBefore.equals(dataAfter)) {
65             LOG.debug("{}: Skipping current(no update): {}", this, id);
66             // No change, ignore
67             return;
68         }
69         updateCurrentAttributes(id, dataBefore, dataAfter, ctx);
70         LOG.debug("{}: Current node updated successfully", this);
71     }
72
73     protected void deleteCurrent(final InstanceIdentifier<D> id, final D dataBefore, final WriteContext ctx)
74         throws WriteFailedException {
75         LOG.debug("{}: Deleting current: {} dataBefore: {}", this, id, dataBefore);
76         deleteCurrentAttributes(id, dataBefore, ctx);
77     }
78
79     @SuppressWarnings("unchecked")
80     @Override
81     public void processModification(@Nonnull final InstanceIdentifier<? extends DataObject> id,
82                                     @Nullable final DataObject dataBefore,
83                                     @Nullable final DataObject dataAfter,
84                                     @Nonnull final WriteContext ctx) throws WriteFailedException {
85         LOG.debug("{}: Updating : {}", this, id);
86         LOG.trace("{}: Updating : {}, from: {} to: {}", this, id, dataBefore, dataAfter);
87
88         checkArgument(idPointsToCurrent(id), "Cannot handle data: %s. Only: %s can be handled by writer: %s",
89                 id, getManagedDataObjectType(), this);
90
91         if (isWrite(dataBefore, dataAfter)) {
92             writeCurrent((InstanceIdentifier<D>) id, castToManaged(dataAfter), ctx);
93         } else if (isDelete(dataBefore, dataAfter)) {
94             deleteCurrent((InstanceIdentifier<D>) id, castToManaged(dataBefore), ctx);
95         } else {
96             checkArgument(dataBefore != null && dataAfter != null, "No data to process");
97             updateCurrent((InstanceIdentifier<D>) id, castToManaged(dataBefore), castToManaged(dataAfter), ctx);
98         }
99     }
100
101     @Override
102     public void validate(@Nonnull final InstanceIdentifier<? extends DataObject> id,
103                          @Nullable final DataObject dataBefore, @Nullable final DataObject dataAfter,
104                          @Nonnull final WriteContext ctx) throws DataValidationFailedException {
105         if (validator == null) {
106             LOG.trace("{}: validator is not defined. Skipping validation for {}", this, id);
107             return;
108         }
109         LOG.trace("{}: Validating : {}, before: {} after: {}", this, id, dataBefore, dataAfter);
110
111         checkArgument(idPointsToCurrent(id), "Cannot handle data: %s. Only: %s can be handled by writer: %s",
112             id, getManagedDataObjectType(), this);
113
114         if (isWrite(dataBefore, dataAfter)) {
115             final D after = castToManaged(dataAfter);
116             validator.validateWrite(getManagedId(id, after), after, ctx);
117         } else if (isDelete(dataBefore, dataAfter)) {
118             final D before = castToManaged(dataBefore);
119             validator.validateDelete(getManagedId(id, before), before, ctx);
120         } else {
121             checkArgument(dataBefore != null && dataAfter != null, "No data to process");
122             if (dataBefore.equals(dataAfter)) {
123                 LOG.debug("{}: Skipping validation (no update) for: {}", this, id);
124                 // No change, ignore
125                 return;
126             }
127             final D before = castToManaged(dataBefore);
128             validator.validateUpdate(getManagedId(id, before), before, castToManaged(dataAfter), ctx);
129         }
130     }
131
132     protected InstanceIdentifier<D> getManagedId(@Nonnull final InstanceIdentifier<? extends DataObject> currentId,
133                                                  @Nonnull final D current) {
134         return (InstanceIdentifier<D>) currentId;
135     }
136
137     private void checkDataType(@Nonnull final DataObject dataAfter) {
138         checkArgument(getManagedDataObjectType().getTargetType().isAssignableFrom(dataAfter.getClass()));
139     }
140
141     private D castToManaged(final DataObject data) {
142         checkDataType(data);
143         return getManagedDataObjectType().getTargetType().cast(data);
144     }
145
146     private static boolean isWrite(final DataObject dataBefore,
147                                     final DataObject dataAfter) {
148         return dataBefore == null && dataAfter != null;
149     }
150
151     private static boolean isDelete(final DataObject dataBefore,
152                                     final DataObject dataAfter) {
153         return dataAfter == null && dataBefore != null;
154     }
155
156     private boolean idPointsToCurrent(final @Nonnull InstanceIdentifier<? extends DataObject> id) {
157         return id.getTargetType().equals(getManagedDataObjectType().getTargetType());
158     }
159
160     protected abstract void writeCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
161                                                    @Nonnull final D data,
162                                                    @Nonnull final WriteContext ctx) throws WriteFailedException;
163
164     protected abstract void deleteCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
165                                                     @Nonnull final D dataBefore,
166                                                     @Nonnull final WriteContext ctx) throws WriteFailedException;
167
168     protected abstract void updateCurrentAttributes(@Nonnull final InstanceIdentifier<D> id,
169                                                     @Nonnull final D dataBefore,
170                                                     @Nonnull final D dataAfter,
171                                                     @Nonnull final WriteContext ctx) throws WriteFailedException;
172
173     @Nonnull
174     @Override
175     public InstanceIdentifier<D> getManagedDataObjectType() {
176         return instanceIdentifier;
177     }
178
179
180     @Override
181     public String toString() {
182         return String.format("Writer[%s]", getManagedDataObjectType().getTargetType().getSimpleName());
183     }
184
185     @Override
186     public boolean supportsDirectUpdate() {
187         return supportsUpdate;
188     }
189 }