6654de2fb545cacd6126c0881b4eba6111c53c41
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / 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.mdsal.binding.dom.codec.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Throwables;
12 import java.lang.invoke.MethodHandle;
13 import java.lang.invoke.MethodHandles;
14 import java.lang.invoke.MethodType;
15 import org.opendaylight.yangtools.concepts.Codec;
16
17 final class ValueContext {
18     private static final MethodType OBJECT_METHOD = MethodType.methodType(Object.class, Object.class);
19     private final Codec<Object, Object> codec;
20     private final MethodHandle getter;
21     private final Class<?> identifier;
22     private final String getterName;
23
24     ValueContext(final Class<?> identifier, final LeafNodeCodecContext <?>leaf) {
25         getterName = leaf.getGetter().getName();
26         try {
27             getter = MethodHandles.publicLookup().unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD);
28         } catch (IllegalAccessException | NoSuchMethodException | SecurityException e) {
29             throw new IllegalStateException(String.format("Cannot find method %s in class %s", getterName, identifier), e);
30         }
31         this.identifier = identifier;
32         codec = leaf.getValueCodec();
33     }
34
35     Object getAndSerialize(final Object obj) {
36         final Object value;
37         try {
38             value = getter.invokeExact(obj);
39         } catch (Throwable e) {
40             Throwables.throwIfUnchecked(e);
41             throw new RuntimeException(e);
42         }
43
44         Preconditions.checkArgument(value != null,
45                 "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
46                 identifier, getterName, obj);
47         return codec.serialize(value);
48     }
49
50     Object deserialize(final Object obj) {
51         return codec.deserialize(obj);
52     }
53
54 }