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.yangtools.binding.data.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.MethodHandles.Lookup;
15 import java.lang.invoke.MethodType;
16 import org.opendaylight.yangtools.concepts.Codec;
17 import org.opendaylight.yangtools.yang.binding.BindingMapping;
19 final class ValueContext {
20 private static final Lookup LOOKUP = MethodHandles.publicLookup();
21 private static final MethodType OBJECT_METHOD = MethodType.methodType(Object.class, Object.class);
22 private final Codec<Object, Object> codec;
23 private final MethodHandle getter;
24 private final Class<?> identifier;
25 private final String getterName;
27 ValueContext(final Class<?> identifier, final LeafNodeCodecContext <?>leaf) {
28 getterName = BindingCodecContext.GETTER_PREFIX + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
30 getter = LOOKUP.unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD);
31 } catch (IllegalAccessException | NoSuchMethodException | SecurityException e) {
32 throw new IllegalStateException(String.format("Cannot find method %s in class %s", getterName, identifier), e);
34 this.identifier = identifier;
35 codec = leaf.getValueCodec();
38 Object getAndSerialize(final Object obj) {
41 value = getter.invokeExact(obj);
42 } catch (Throwable e) {
43 throw Throwables.propagate(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);