2 * Copyright (c) 2017 Pantheon Technologies s.r.o. 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.javav2.dom.codec.impl.context;
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Throwables;
13 import java.lang.invoke.MethodHandle;
14 import java.lang.invoke.MethodHandles;
15 import java.lang.invoke.MethodType;
16 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base.LeafNodeCodecContext;
17 import org.opendaylight.yangtools.concepts.Codec;
20 * Context for serialize/deserialize leaf.
23 public final class ValueContext {
25 private static final MethodType OBJECT_METHOD = MethodType.methodType(Object.class, Object.class);
26 private final Codec<Object, Object> codec;
27 private final MethodHandle getter;
28 private final Class<?> identifier;
29 private final String getterName;
32 * Prepare codec of leaf value and getter of binding leaf object for getting leaf.
37 * - leaf codec context
39 public ValueContext(final Class<?> identifier, final LeafNodeCodecContext<?> leaf) {
40 getterName = leaf.getGetter().getName();
42 getter = MethodHandles.publicLookup().unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD);
43 } catch (IllegalAccessException | NoSuchMethodException | SecurityException e) {
44 throw new IllegalStateException(String.format("Cannot find method %s in class %s", getterName, identifier), e);
46 this.identifier = identifier;
47 codec = leaf.getValueCodec();
51 * Get object via invoking getter with input and serializes it by prepared codec of leaf.
55 * @return serialized invoked object
57 public Object getAndSerialize(final Object obj) {
60 value = getter.invokeExact(obj);
61 } catch (final Throwable e) {
62 throw Throwables.propagate(e);
65 Preconditions.checkArgument(value != null,
66 "All keys must be specified for %s. Missing key is %s. Supplied key is %s",
67 identifier, getterName, obj);
68 return codec.serialize(value);
72 * Deserialize input object by prepared codec.
76 * @return deserialized object
78 public Object deserialize(final Object obj) {
79 return codec.deserialize(obj);