Bug 1439, Bug 1443 Binding Codec NormalizedNodeWriter support
[yangtools.git] / code-generator / binding-data-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / EncapsulatedValueCodec.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.binding.data.codec.impl;
9
10 import java.lang.reflect.Constructor;
11 import java.lang.reflect.InvocationTargetException;
12 import java.lang.reflect.Method;
13 import java.util.concurrent.Callable;
14
15 /**
16  *
17  * Derived YANG types are just immutable value holders for simple value
18  * types, which are same as in NormalizedNode model.
19  *
20  */
21 class EncapsulatedValueCodec extends ReflectionBasedCodec {
22
23     private final Method getter;
24     private final Constructor<?> constructor;
25
26     EncapsulatedValueCodec(final Class<?> typeClz) {
27         super(typeClz);
28         try {
29             this.getter = typeClz.getMethod("getValue");
30             this.constructor = typeClz.getConstructor(getter.getReturnType());
31         } catch (NoSuchMethodException | SecurityException e) {
32             throw new IllegalStateException("Could not resolve required method.", e);
33         }
34     }
35
36     static Callable<ReflectionBasedCodec> loader(final Class<?> typeClz) {
37         return new Callable<ReflectionBasedCodec>() {
38             @Override
39             public ReflectionBasedCodec call() throws Exception {
40                 return new EncapsulatedValueCodec(typeClz);
41             }
42         };
43     }
44
45     @Override
46     public Object deserialize(final Object input) {
47         try {
48             return constructor.newInstance(input);
49         } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
50             throw new IllegalStateException(e);
51         }
52     }
53
54     @Override
55     public Object serialize(final Object input) {
56         try {
57             return getter.invoke(input);
58         } catch (IllegalAccessException | InvocationTargetException e) {
59             throw new IllegalStateException(e);
60         }
61     }
62 }