2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
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;
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;
24 ValueContext(final Class<?> identifier, final ValueNodeCodecContext leaf) {
25 getterName = leaf.getGetterName();
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),
32 this.identifier = identifier;
33 codec = leaf.getValueCodec();
36 @SuppressWarnings("checkstyle:illegalCatch")
37 Object getAndSerialize(final Object obj) {
40 value = getter.invokeExact(obj);
41 } catch (Throwable e) {
42 Throwables.throwIfUnchecked(e);
43 throw new IllegalStateException(e);
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);
52 Object deserialize(final Object obj) {
53 return codec.deserialize(obj);