2 * Copyright (c) 2014 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.MethodHandles.Lookup;
15 import java.lang.invoke.MethodType;
16 import java.lang.reflect.Method;
17 import java.util.concurrent.Callable;
18 import org.opendaylight.mdsal.binding.dom.codec.impl.ValueTypeCodec.SchemaUnawareCodec;
21 * Derived YANG types are just immutable value holders for simple value
22 * types, which are same as in NormalizedNode model.
24 final class EncapsulatedValueCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
25 private static final Lookup LOOKUP = MethodHandles.publicLookup();
26 private static final MethodType OBJ_METHOD = MethodType.methodType(Object.class, Object.class);
27 private final MethodHandle constructor;
28 private final MethodHandle getter;
29 private final Class<?> valueType;
31 private EncapsulatedValueCodec(final Class<?> typeClz, final MethodHandle constructor, final MethodHandle getter,
32 final Class<?> valueType) {
34 this.constructor = Preconditions.checkNotNull(constructor);
35 this.getter = Preconditions.checkNotNull(getter);
36 this.valueType = Preconditions.checkNotNull(valueType);
39 static Callable<EncapsulatedValueCodec> loader(final Class<?> typeClz) {
41 final Method m = typeClz.getMethod("getValue");
42 final MethodHandle getter = LOOKUP.unreflect(m).asType(OBJ_METHOD);
43 final Class<?> valueType = m.getReturnType();
45 final MethodHandle constructor = LOOKUP.findConstructor(typeClz,
46 MethodType.methodType(void.class, valueType)).asType(OBJ_METHOD);
47 return new EncapsulatedValueCodec(typeClz, constructor, getter, valueType);
52 * Quick check if a value object has a chance to deserialize using {@link #deserialize(Object)}.
54 * @param value Value to be checked
55 * @return True if the value can be encapsulated
57 boolean canAcceptObject(final Object value) {
58 return valueType.isInstance(value);
62 @SuppressWarnings("checkstyle:illegalCatch")
63 public Object deserialize(final Object input) {
65 return constructor.invokeExact(input);
66 } catch (Throwable e) {
67 Throwables.throwIfUnchecked(e);
68 throw new RuntimeException(e);
73 @SuppressWarnings("checkstyle:illegalCatch")
74 public Object serialize(final Object input) {
76 return getter.invokeExact(input);
77 } catch (Throwable e) {
78 Throwables.throwIfUnchecked(e);
79 throw new RuntimeException(e);