33e0582f2a24dbc638237fd96da30c8ed9cb6f25
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / DirectGetterRouteContextExtractor.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 DirectGetterRouteContextExtractor extends ContextReferenceExtractor {
20
21     private final static Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup();
22     private final MethodHandle handle;
23
24     private DirectGetterRouteContextExtractor(final MethodHandle rawHandle) {
25         handle = rawHandle.asType(MethodType.methodType(InstanceIdentifier.class, DataObject.class));
26     }
27
28     static final ContextReferenceExtractor create(final Method getterMethod) throws IllegalAccessException {
29         final MethodHandle getterHandle = PUBLIC_LOOKUP.unreflect(getterMethod);
30         return new DirectGetterRouteContextExtractor(getterHandle);
31     }
32
33     @Override
34     InstanceIdentifier<?> extract(final DataObject obj) {
35         try {
36             return (InstanceIdentifier<?>) handle.invokeExact(obj);
37         } catch (final Throwable e) {
38             throw Throwables.propagate(e);
39         }
40     }
41
42 }