9c2ae02c397c529adad2aace2ef780c6638fc64b
[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),
30                 e);
31         }
32         this.identifier = identifier;
33         codec = leaf.getValueCodec();
34     }
35
36     @SuppressWarnings("checkstyle:illegalCatch")
37     Object getAndSerialize(final Object obj) {
38         final Object value;
39         try {
40             value = getter.invokeExact(obj);
41         } catch (Throwable e) {
42             Throwables.throwIfUnchecked(e);
43             throw new RuntimeException(e);
44         }
45
46         Preconditions.checkArgument(value != null,
47                 "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
48                 identifier, getterName, obj);
49         return codec.serialize(value);
50     }
51
52     Object deserialize(final Object obj) {
53         return codec.deserialize(obj);
54     }
55
56 }