Bug 2351 Speed-up Binding-to-Binding routed RPC Invocation.
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / GetValueRouteContextExtractor.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the terms of the Eclipse
5  * Public License v1.0 which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.md.sal.binding.impl;
9
10 import com.google.common.base.Throwables;
11 import java.lang.invoke.MethodHandle;
12 import java.lang.invoke.MethodHandles;
13 import java.lang.invoke.MethodHandles.Lookup;
14 import java.lang.invoke.MethodType;
15 import java.lang.reflect.Method;
16 import org.opendaylight.yangtools.yang.binding.DataObject;
17 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
18
19 final class GetValueRouteContextExtractor extends ContextReferenceExtractor {
20
21     private final static Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup();
22     private final MethodHandle contextHandle;
23     private final MethodHandle valueHandle;
24
25     private GetValueRouteContextExtractor(final MethodHandle rawContextHandle, final MethodHandle rawValueHandle) {
26         contextHandle = rawContextHandle.asType(MethodType.methodType(Object.class, DataObject.class));
27         valueHandle = rawValueHandle.asType(MethodType.methodType(InstanceIdentifier.class, Object.class));
28     }
29
30     public static ContextReferenceExtractor create(final Method contextGetter, final Method getValueMethod)
31             throws IllegalAccessException {
32         final MethodHandle rawContextHandle = PUBLIC_LOOKUP.unreflect(contextGetter);
33         final MethodHandle rawValueHandle = PUBLIC_LOOKUP.unreflect(getValueMethod);
34         return new GetValueRouteContextExtractor(rawContextHandle, rawValueHandle);
35     }
36
37     @Override
38     InstanceIdentifier<?> extract(final DataObject obj) {
39         try {
40             final Object ctx = contextHandle.invokeExact(obj);
41             if (ctx != null) {
42                 return (InstanceIdentifier<?>) valueHandle.invokeExact(ctx);
43             }
44             return null;
45         } catch (final Throwable e) {
46             throw Throwables.propagate(e);
47         }
48     }
49
50
51 }