Get rid of CheckedFutures
[mdsal.git] / binding2 / mdsal-binding2-dom-adapter / src / main / java / org / opendaylight / mdsal / binding / javav2 / dom / adapter / extractor / GetValueRouteContextExtractor.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.javav2.dom.adapter.extractor;
9
10 import com.google.common.annotations.Beta;
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 org.opendaylight.mdsal.binding.javav2.spec.base.InstanceIdentifier;
18 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
19
20 @Beta
21 final class GetValueRouteContextExtractor extends ContextReferenceExtractor {
22
23     private static final Lookup PUBLIC_LOOKUP = MethodHandles.publicLookup();
24
25     private final MethodHandle contextHandle;
26     private final MethodHandle valueHandle;
27
28     private GetValueRouteContextExtractor(final MethodHandle rawContextHandle, final MethodHandle rawValueHandle) {
29         contextHandle = rawContextHandle.asType(MethodType.methodType(Object.class, TreeNode.class));
30         valueHandle = rawValueHandle.asType(MethodType.methodType(InstanceIdentifier.class, Object.class));
31     }
32
33     static ContextReferenceExtractor create(final Method contextGetter, final Method getValueMethod)
34             throws IllegalAccessException {
35         final MethodHandle rawContextHandle = PUBLIC_LOOKUP.unreflect(contextGetter);
36         final MethodHandle rawValueHandle = PUBLIC_LOOKUP.unreflect(getValueMethod);
37         return new GetValueRouteContextExtractor(rawContextHandle, rawValueHandle);
38     }
39
40     @SuppressWarnings("checkstyle:IllegalCatch")
41     @Override
42     public InstanceIdentifier<? extends TreeNode> extract(final TreeNode obj) {
43         try {
44             final Object ctx = contextHandle.invokeExact(obj);
45             if (ctx != null) {
46                 return (InstanceIdentifier<? extends TreeNode>) valueHandle.invokeExact(ctx);
47             }
48             return null;
49         } catch (final Throwable e) {
50             Throwables.throwIfUnchecked(e);
51             throw new RuntimeException(e);
52         }
53     }
54 }
55