Example usage for java.lang.invoke MethodType MethodType

List of usage examples for java.lang.invoke MethodType MethodType

Introduction

In this page you can find the example usage for java.lang.invoke MethodType MethodType.

Prototype

private MethodType(Class<?> rtype, Class<?>[] ptypes) 

Source Link

Document

Constructor that performs no copying or validation.

Usage

From source file:com.haulmont.cuba.core.config.ConfigDefaultMethod.java

@Override
public Object invoke(ConfigHandler handler, Object[] args, Object proxy) {
    try {/*from w ww .  jav  a2s  . c  om*/
        if (SystemUtils.IS_JAVA_1_8) {
            // hack to invoke default method of an interface reflectively
            Constructor<MethodHandles.Lookup> lookupConstructor = MethodHandles.Lookup.class
                    .getDeclaredConstructor(Class.class, Integer.TYPE);
            if (!lookupConstructor.isAccessible()) {
                lookupConstructor.setAccessible(true);
            }
            return lookupConstructor.newInstance(configInterface, MethodHandles.Lookup.PRIVATE)
                    .unreflectSpecial(configMethod, configInterface).bindTo(proxy).invokeWithArguments(args);
        } else {
            return MethodHandles.lookup()
                    .findSpecial(configInterface, configMethod.getName(),
                            MethodType.methodType(configMethod.getReturnType(),
                                    configMethod.getParameterTypes()),
                            configInterface)
                    .bindTo(proxy).invokeWithArguments(args);
        }
    } catch (Throwable throwable) {
        throw new RuntimeException("Error invoking default method of config interface", throwable);
    }
}

From source file:de.zib.sfs.WrappedFSDataInputStream.java

/**
 * Gets the datanode that was last read from as a string. Should be called
 * after the first read operation has been performed.
 * //  w w  w  . j av a  2s.  c o  m
 * @return "->" + hostname of the datanode, or empty string if the
 *         information is not available
 */
private String getDatanodeHostNameString() {
    if (this.datanodeHostnameSupplier == null) {
        if (this.in instanceof HdfsDataInputStream) {
            // call Hadoop's method directly
            final HdfsDataInputStream hdfsIn = (HdfsDataInputStream) this.in;
            if (hdfsIn.getCurrentDatanode() != null) {
                this.datanodeHostnameSupplier = () -> hdfsIn.getCurrentDatanode().getHostName();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Using datanodeHostNameSupplier from Hadoop.");
                }
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("datanodeHostNameSupplier from Hadoop has no DataNode information.");
                }
                this.datanodeHostnameSupplier = () -> "";
            }
        } else {
            try {
                // Check if there's an appropriately named method available
                // that returns the hostname of the current node that is
                // being read from. Using the lambda factory provides almost
                // direct invocation performance.
                MethodHandles.Lookup methodHandlesLookup = MethodHandles.lookup();

                // try this stream or the one it wraps
                Method getCurrentDatanodeHostNameMethod = null;
                InputStream bindToStream = null;
                try {
                    getCurrentDatanodeHostNameMethod = this.in.getClass()
                            .getDeclaredMethod("getCurrentDatanodeHostName");
                    bindToStream = this.in;
                } catch (NoSuchMethodException e) {
                    getCurrentDatanodeHostNameMethod = this.in.getWrappedStream().getClass()
                            .getDeclaredMethod("getCurrentDatanodeHostName");
                    bindToStream = this.in.getWrappedStream();
                }

                MethodHandle datanodeHostNameSupplierTarget = LambdaMetafactory.metafactory(methodHandlesLookup,
                        "get", MethodType.methodType(Supplier.class, bindToStream.getClass()),
                        MethodType.methodType(Object.class),
                        methodHandlesLookup.unreflect(getCurrentDatanodeHostNameMethod),
                        MethodType.methodType(Object.class)).getTarget();
                this.datanodeHostnameSupplier = (Supplier<String>) datanodeHostNameSupplierTarget
                        .bindTo(bindToStream).invoke();

                if (LOG.isDebugEnabled()) {
                    LOG.debug("Using 'getCurrentDatanodeHostName' as datanodeHostNameSupplier.");
                }
            } catch (Throwable t) {
                this.datanodeHostnameSupplier = () -> "";
                if (LOG.isDebugEnabled()) {
                    LOG.debug("No datanodeHostNameSupplier available.", t);
                }
            }
        }
    }

    // handle cases where we have to perform a reverse lookup if
    // hostname is an IP
    String dnHostname = this.datanodeHostnameSupplier.get();
    String cachedHostname = HOSTNAME_CACHE.get(dnHostname);
    if (cachedHostname == null) {
        try {
            // strip port if necessary
            int portIndex = dnHostname.indexOf(":");
            cachedHostname = InetAddress
                    .getByName(portIndex == -1 ? dnHostname : dnHostname.substring(0, portIndex)).getHostName();
        } catch (UnknownHostException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Could not determine hostname for " + dnHostname, e);
            }
            cachedHostname = "";
        }
        HOSTNAME_CACHE.put(dnHostname, cachedHostname);
    }
    return cachedHostname;
}

From source file:org.openo.nfvo.resmanagement.common.util.RestfulUtil.java

/**
 * encapsulate the java reflect exception.<br>
 *
 * @param methodName, Restful's method.//w ww . j av  a  2 s .  c o m
 * @param objects, method param array.
 * @return
 * @since NFVO 0.5
 */
public static RestfulResponse getRestRes(String methodName, Object... objects) {
    try {
        if (objects == null || REST_CLIENT == null) {
            return null;
        }

        Class<?>[] classes = new Class[objects.length];
        for (int i = 0; i < objects.length; i++) {
            classes[i] = objects[i].getClass();
        }
        if (methodName.startsWith("async")) {
            classes[classes.length - 1] = RestfulAsyncCallback.class;
        }

        Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
        MethodType mt = MethodType.methodType(rtType, classes);
        Object result = MethodHandles.lookup().findVirtual(REST_CLIENT.getClass(), methodName, mt)
                .bindTo(REST_CLIENT).invokeWithArguments(objects);
        if (result != null) {
            return (RestfulResponse) result;
        }
        LOGGER.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.",
                methodName);
        return null;
    } catch (ReflectiveOperationException e) {
        LOGGER.error("function=getRestRes, msg=error occurs, e={}.", e);
    } catch (Throwable e) {// NOSONAR
        LOGGER.error("function=getRestRes, msg=Throwable, e={}.", e);
        try {
            throw (ServiceException) new ServiceException().initCause(e.getCause());
        } catch (ServiceException se) {
            LOGGER.error("function=getRestRes, msg=ServiceException occurs, e={}.", se);
        }
    }
    return null;
}

From source file:org.openo.nfvo.vnfmadapter.common.ResultRequestUtil.java

/**
 * common method//from  w w  w  . j a  v a  2s .co m
 * <br/>
 *
 * @param vnfmObject
 * @param path
 *            url defined
 * @param methodName
 *            [get, put, delete, post]
 * @param paramsJson
 *            raw data with json format, if <code>methodName</code> is get
 *            or delete, fill it with null
 * @return
 * @since NFVO 0.5
 */
public static JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson) {
    JSONObject resultJson = new JSONObject();

    ConnectMgrVnfm mgrVcmm = new ConnectMgrVnfm();

    if (Constant.HTTP_OK != mgrVcmm.connect(vnfmObject)) {
        resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR);
        resultJson.put("data", "connect fail.");
        return resultJson;
    }

    HttpMethod httpMethod = null;
    try {

        String result = null;
        String vnfPath = path.contains("%s") ? String.format(path, mgrVcmm.getRoaRand()) : path;
        LOG.info("function=call, msg=url is {}, session is {}", vnfmObject.getString("url") + vnfPath,
                mgrVcmm.getAccessSession());
        HttpRequests.Builder builder = new HttpRequests.Builder(Constant.ANONYMOUS)
                .addHeader(Constant.ACCESSSESSION, mgrVcmm.getAccessSession())
                .setUrl(vnfmObject.getString("url"), vnfPath).setParams(paramsJson);
        MethodType methodType = MethodType.methodType(HttpRequests.Builder.class, new Class[0]);
        MethodHandle mt = MethodHandles.lookup().findVirtual(builder.getClass(), methodName, methodType)
                .bindTo(builder);

        builder = (HttpRequests.Builder) mt.invoke();
        httpMethod = builder.execute();
        result = httpMethod.getResponseBodyAsString();
        LOG.warn("function=call, msg=response status is {}. result is {}", httpMethod.getStatusCode(), result);
        resultJson.put(Constant.RETCODE, httpMethod.getStatusCode());
        resultJson.put("data", result);
    } catch (IOException e) {
        LOG.info("function=call, msg=IOException, e is {}", e);
    } catch (ReflectiveOperationException e) {
        LOG.info("function=call, msg=ReflectiveOperationException, e is {}", e);
    } catch (Throwable e) {
        LOG.info("function=call, msg=Throwable, e is {}", e);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }

    if (httpMethod == null) {
        resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR);
        resultJson.put("data", "get connection error");
    }

    return resultJson;
}

From source file:org.openo.nfvo.vnfmadapter.common.ResultRequestUtil.java

/**
 * common method/*from w  w w  .j av  a2  s  .co  m*/
 * <br/>
 *
 * @param vnfmObject
 * @param path
 *            url defined
 * @param methodName
 *            [get, put, delete, post]
 * @param paramsJson
 *            raw data with json format, if <code>methodName</code> is get
 *            or delete, fill it with null
 * @return
 * @since NFVO 0.5
 */
public static JSONObject call(JSONObject vnfmObject, String path, String methodName, String paramsJson,
        String authModel) {
    LOG.info("request-param=" + paramsJson + ",authModel=" + authModel + ",path=" + path + ",vnfmInfo="
            + vnfmObject);
    JSONObject resultJson = new JSONObject();

    ConnectMgrVnfm mgrVcmm = new ConnectMgrVnfm();

    if (Constant.HTTP_OK != mgrVcmm.connect(vnfmObject, authModel)) {
        resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR);
        resultJson.put("data", "connect fail.");
        return resultJson;
    }

    HttpMethod httpMethod = null;
    try {

        String result = null;
        String vnfPath = path.contains("%s") ? String.format(path, mgrVcmm.getRoaRand()) : path;
        LOG.info("function=call, msg=url is {}, session is {}", vnfmObject.getString("url") + vnfPath,
                mgrVcmm.getAccessSession());
        HttpRequests.Builder builder = new HttpRequests.Builder(authModel)
                .addHeader(Constant.ACCESSSESSION, mgrVcmm.getAccessSession())
                .setUrl(vnfmObject.getString("url"), vnfPath).setParams(paramsJson);
        MethodType methodType = MethodType.methodType(HttpRequests.Builder.class, new Class[0]);
        MethodHandle mt = MethodHandles.lookup().findVirtual(builder.getClass(), methodName, methodType)
                .bindTo(builder);

        builder = (HttpRequests.Builder) mt.invoke();
        httpMethod = builder.execute();
        result = httpMethod.getResponseBodyAsString();
        LOG.warn("function=call, msg=response status is {}. result is {}", httpMethod.getStatusCode(), result);
        resultJson.put(Constant.RETCODE, httpMethod.getStatusCode());
        resultJson.put("data", result);

        // logout delete tokens
        String token = mgrVcmm.getAccessSession();
        String roaRand = mgrVcmm.getRoaRand();
        String vnfmUrl = vnfmObject.getString("url");
        removeTokens(vnfmUrl, token, roaRand);
    } catch (IOException e) {
        LOG.info("function=call, msg=IOException, e is {}", e);
    } catch (ReflectiveOperationException e) {
        LOG.info("function=call, msg=ReflectiveOperationException, e is {}", e);
    } catch (Throwable e) {
        LOG.info("function=call, msg=Throwable, e is {}", e);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }

    if (httpMethod == null) {
        resultJson.put(Constant.RETCODE, Constant.HTTP_INNERERROR);
        resultJson.put("data", "get connection error");
    }

    return resultJson;
}