Merge "BUG-997 Fix unused argument in SchemaResolutionException"
[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 import org.opendaylight.yangtools.binding.data.codec.impl.ValueTypeCodec.SchemaUnawareCodec;
15
16 /**
17  *
18  * Derived YANG types are just immutable value holders for simple value
19  * types, which are same as in NormalizedNode model.
20  *
21  */
22 class EncapsulatedValueCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
23
24     private final Method getter;
25     private final Constructor<?> constructor;
26
27     EncapsulatedValueCodec(final Class<?> typeClz) {
28         super(typeClz);
29         try {
30             this.getter = typeClz.getMethod("getValue");
31             this.constructor = typeClz.getConstructor(getter.getReturnType());
32         } catch (NoSuchMethodException | SecurityException e) {
33             throw new IllegalStateException("Could not resolve required method.", e);
34         }
35     }
36
37     static Callable<EncapsulatedValueCodec> loader(final Class<?> typeClz) {
38         return new Callable<EncapsulatedValueCodec>() {
39             @Override
40             public EncapsulatedValueCodec call() throws Exception {
41                 return new EncapsulatedValueCodec(typeClz);
42             }
43         };
44     }
45
46     @Override
47     public Object deserialize(final Object input) {
48         try {
49             return constructor.newInstance(input);
50         } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
51             throw new IllegalStateException(e);
52         }
53     }
54
55     @Override
56     public Object serialize(final Object input) {
57         try {
58             return getter.invoke(input);
59         } catch (IllegalAccessException | InvocationTargetException e) {
60             throw new IllegalStateException(e);
61         }
62     }
63 }