3d5f9f4e8191ec8add0e6a0d80994138917f61ed
[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 com.google.common.base.Optional;
20 import com.google.common.base.Preconditions;
21 import io.fd.honeycomb.v3po.translate.util.ReflectionUtils;
22 import io.fd.honeycomb.v3po.translate.spi.read.ChildReaderCustomizer;
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25 import java.util.Collections;
26 import org.opendaylight.yangtools.concepts.Builder;
27 import org.opendaylight.yangtools.yang.binding.DataObject;
28
29 /**
30  * Might be slow !
31  */
32 public class ReflexiveChildReaderCustomizer<C extends DataObject, B extends Builder<C>>
33     extends ReflexiveRootReaderCustomizer<C, B>
34     implements ChildReaderCustomizer<C,B> {
35
36     public ReflexiveChildReaderCustomizer(final Class<B> builderClass) {
37         super(builderClass);
38     }
39
40     // TODO Could be just a default implementation in interface (making this a mixin)
41
42     @Override
43     public void merge(final Builder<? extends DataObject> parentBuilder, final C readValue) {
44         final Optional<Method> method =
45             ReflectionUtils.findMethodReflex(parentBuilder.getClass(), "set",
46                 Collections.<Class<?>>singletonList(readValue.getClass()), parentBuilder.getClass());
47
48         Preconditions.checkArgument(method.isPresent(), "Unable to set %s to %s", readValue, parentBuilder);
49
50         try {
51             method.get().invoke(parentBuilder, readValue);
52         } catch (IllegalAccessException | InvocationTargetException e) {
53             throw new IllegalArgumentException("Unable to set " + readValue + " to " + parentBuilder, e);
54         }
55     }
56
57 }