Split out codecs from BindingCodecContext
[yangtools.git] / code-generator / binding-data-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / ValueContext.java
1 /*
2  * Copyright (c) 2015 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 com.google.common.base.Preconditions;
11 import java.lang.reflect.InvocationTargetException;
12 import java.lang.reflect.Method;
13 import org.opendaylight.yangtools.concepts.Codec;
14 import org.opendaylight.yangtools.yang.binding.BindingMapping;
15
16 final class ValueContext {
17     private final Codec<Object, Object> codec;
18     private final Method getter;
19
20     ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
21         final String getterName = BindingCodecContext.GETTER_PREFIX
22                 + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
23         try {
24             getter = identifier.getMethod(getterName);
25         } catch (NoSuchMethodException | SecurityException e) {
26             throw new IllegalStateException(e);
27         }
28         codec = leaf.getValueCodec();
29     }
30
31     Object getAndSerialize(final Object obj) {
32         try {
33             final Object value = getter.invoke(obj);
34             Preconditions.checkArgument(value != null,
35                     "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
36                     getter.getDeclaringClass(), getter.getName(), obj);
37             return codec.serialize(value);
38         } catch (IllegalAccessException | InvocationTargetException e) {
39             throw new IllegalArgumentException(e);
40         }
41     }
42
43     Object deserialize(final Object obj) {
44         return codec.deserialize(obj);
45     }
46
47 }