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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verifyNotNull;
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 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
19 final class ValueContext {
20 private static final MethodType OBJECT_METHOD = MethodType.methodType(Object.class, Object.class);
21 private final IllegalArgumentCodec<Object, Object> codec;
22 private final MethodHandle getter;
23 private final Class<?> identifier;
24 private final String getterName;
26 ValueContext(final Class<?> identifier, final ValueNodeCodecContext leaf) {
27 getterName = leaf.getGetterName();
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),
34 this.identifier = identifier;
35 codec = leaf.getValueCodec();
38 @SuppressWarnings("checkstyle:illegalCatch")
39 Object getAndSerialize(final Object obj) {
42 value = getter.invokeExact(obj);
43 } catch (Throwable e) {
44 Throwables.throwIfUnchecked(e);
45 throw new IllegalStateException(e);
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);
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,