38107edff95bbb90c4c531e389322359ce97fb47
[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.util.read;
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.spi.read.ChildReaderCustomizer;
24 import io.fd.honeycomb.v3po.translate.util.ReflectionUtils;
25 import java.lang.reflect.InvocationTargetException;
26 import java.lang.reflect.Method;
27 import org.opendaylight.yangtools.concepts.Builder;
28 import org.opendaylight.yangtools.yang.binding.Augmentation;
29 import org.opendaylight.yangtools.yang.binding.DataObject;
30
31 /**
32  * Might be slow !
33  */
34 public class ReflexiveAugmentReaderCustomizer<C extends DataObject, B extends Builder<C>>
35     extends ReflexiveRootReaderCustomizer<C, B>
36     implements ChildReaderCustomizer<C,B> {
37
38     private final Class<C> augType;
39
40     public ReflexiveAugmentReaderCustomizer(final Class<B> builderClass, final Class<C> augType) {
41         super(builderClass);
42         this.augType = augType;
43     }
44
45     @Override
46     public void merge(final Builder<? extends DataObject> parentBuilder, final C readValue) {
47         final Optional<Method> method =
48             ReflectionUtils.findMethodReflex(parentBuilder.getClass(), "addAugmentation",
49                 Lists.newArrayList(Class.class, Augmentation.class), parentBuilder.getClass());
50
51         checkArgument(method.isPresent(), "Not possible to add augmentations to builder: %s", parentBuilder);
52         try {
53             method.get().invoke(parentBuilder, augType, readValue);
54         } catch (IllegalAccessException | InvocationTargetException e) {
55             throw new IllegalArgumentException("Unable to set " + readValue + " to " + parentBuilder, e);
56         }
57     }
58
59 }