Bump versions to 14.0.0-SNAPSHOT
[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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
12
13 import com.google.common.base.Throwables;
14 import java.lang.invoke.MethodHandle;
15 import java.lang.invoke.MethodHandles;
16 import java.lang.invoke.MethodType;
17
18 final class ValueContext {
19     private static final MethodType OBJECT_METHOD = MethodType.methodType(Object.class, Object.class);
20
21     private final ValueCodec<Object, Object> codec;
22     private final MethodHandle getter;
23     private final Class<?> identifier;
24     private final String getterName;
25
26     ValueContext(final Class<?> identifier, final ValueNodeCodecContext leaf) {
27         getterName = leaf.getGetterName();
28         try {
29             getter = MethodHandles.publicLookup().unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD);
30         } catch (IllegalAccessException | NoSuchMethodException e) {
31             throw new IllegalStateException(String.format("Cannot find method %s in class %s", getterName, identifier),
32                 e);
33         }
34         this.identifier = identifier;
35         codec = leaf.getValueCodec();
36     }
37
38     @SuppressWarnings("checkstyle:illegalCatch")
39     Object getAndSerialize(final Object obj) {
40         final Object value;
41         try {
42             value = getter.invokeExact(obj);
43         } catch (Throwable e) {
44             Throwables.throwIfUnchecked(e);
45             throw new IllegalStateException(e);
46         }
47
48         checkArgument(value != null, "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
49                 identifier, getterName, obj);
50         return codec.serialize(value);
51     }
52
53     Object deserialize(final Object obj) {
54         checkArgument(obj != null, "Attempted to serialize null for %s component of %s", getterName, identifier);
55         return verifyNotNull(codec.deserialize(obj), "Codec for %s of %s returned null for %s", getterName, identifier,
56             obj);
57     }
58 }