Example usage for org.springframework.util ReflectionUtils invokeMethod

List of usage examples for org.springframework.util ReflectionUtils invokeMethod

Introduction

In this page you can find the example usage for org.springframework.util ReflectionUtils invokeMethod.

Prototype

@Nullable
public static Object invokeMethod(Method method, @Nullable Object target, @Nullable Object... args) 

Source Link

Document

Invoke the specified Method against the supplied target object with the supplied arguments.

Usage

From source file:org.motechproject.server.event.annotations.MotechListenerNamedParametersProxy.java

@Override
public void callHandler(MotechEvent event) {
    List<Object> args = new ArrayList<Object>();
    Class<?>[] paramTypes = method.getParameterTypes();
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    Assert.isTrue(paramTypes.length == paramAnnotations.length);
    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> t = paramTypes[i];
        Assert.notEmpty(paramAnnotations[i], "MotechParam(name) annotation is required for each parameter.");
        //TODO now assuming only MotechParam annotation is present...
        Assert.isAssignable(MotechParam.class, paramAnnotations[i][0].getClass());
        MotechParam annotation = (MotechParam) paramAnnotations[i][0];
        Object arg = event.getParameters().get(annotation.value());
        Assert.notNull(arg, String.format("parameter #%d with name:\"%s\" not found or null prameter passed.",
                i, annotation.value()));
        Assert.isAssignable(t, arg.getClass(), String.format("Parameter #%d expected subtypes of %s passed %s.",
                i, t.getName(), arg.getClass().getName()));
        args.add(arg);//from w  ww.  j a v  a  2 s  .  c om
    }
    ReflectionUtils.invokeMethod(method, bean, args.toArray());

}

From source file:org.grails.datastore.mapping.engine.EntityAccess.java

public void setPropertyNoConversion(String name, Object value) {
    final PropertyDescriptor pd = beanWrapper.getPropertyDescriptor(name);
    if (pd == null) {
        return;//  w  w w .  ja v  a2  s  . co m
    }
    final Method writeMethod = pd.getWriteMethod();
    if (writeMethod != null) {
        ReflectionUtils.invokeMethod(writeMethod, beanWrapper.getWrappedInstance(), value);
    }
}

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebServletListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {//  w  w w . ja  v a  2  s. c om
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        //need to put the following class to WebAppClassLoader, to share it between for web and core
        contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory");

        ServletContext servletContext = sce.getServletContext();
        String dependenciesFile;
        try {
            dependenciesFile = IOUtils.toString(servletContext.getResourceAsStream("/WEB-INF/web.dependencies"),
                    "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException("An error occurred while loading dependencies file", e);
        }

        String[] dependenciesNames = dependenciesFile.split("\\n");
        URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> {
            try {
                return servletContext.getResource("/WEB-INF/lib/" + name);
            } catch (MalformedURLException e) {
                throw new RuntimeException("An error occurred while loading dependency " + name, e);
            }
        }).toArray(URL[]::new);
        URLClassLoader webClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader);

        Thread.currentThread().setContextClassLoader(webClassLoader);
        Class<?> appContextLoaderClass = webClassLoader.loadClass(getAppContextLoaderClassName());
        appContextLoader = appContextLoaderClass.newInstance();

        Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames",
                String.class);
        ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile);

        Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass,
                "contextInitialized", ServletContextEvent.class);
        ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce);

        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("An error occurred while starting single WAR application", e);
    }
}

From source file:org.shept.persistence.provider.hibernate.HibernateUtils_old.java

public static Object copyTemplate(HibernateDaoSupport dao, Object entityModelTemplate) {
    if (entityModelTemplate != null) {
        // hier besser die Metadaten von Hibernate fragen
        if (null != getClassMetadata(dao, entityModelTemplate)) {
            //         if (null != AnnotationUtils.findAnnotation(entityModelTemplate.getClass(), Entity.class)) {
            String idName = HibernateUtils_old.getIdentifierPropertyName(dao, entityModelTemplate);
            Object newModel = BeanUtils.instantiateClass(entityModelTemplate.getClass());
            BeanUtils.copyProperties(entityModelTemplate, newModel, new String[] { idName });

            Serializable idx = getIdValue(dao, entityModelTemplate);

            ClassMetadata meta = getClassMetadata(dao, idx);
            Type type = meta.getIdentifierType();

            if (meta != null && type.isComponentType()) {
                // alternaitv               if (id != null && (null != AnnotationUtils.findAnnotation(id.getClass(), Embeddable.class))) {
                Serializable copyId = BeanUtils.instantiate(idx.getClass());
                BeanUtils.copyProperties(idx, copyId);
                Method idMth = ReflectionUtils.findMethod(entityModelTemplate.getClass(),
                        "set" + StringUtils.capitalize(idName), new Class[] {});
                if (idMth != null) {
                    ReflectionUtils.invokeMethod(idMth, newModel, copyId);
                }/*from   www .ja  v a2 s  .co  m*/
            }
            return newModel;
        }
    }
    return null;
}

From source file:com.haulmont.cuba.core.sys.singleapp.SingleAppCoreServletListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {//from  w ww.j a  v  a  2 s  . co  m
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        //need to put the following class to WebAppClassLoader, to share it between for web and core
        contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory");

        ServletContext servletContext = sce.getServletContext();
        String dependenciesFile;
        try {
            dependenciesFile = IOUtils
                    .toString(servletContext.getResourceAsStream("/WEB-INF/core.dependencies"), "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException("An error occurred while loading dependencies file", e);
        }

        String[] dependenciesNames = dependenciesFile.split("\\n");
        URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> {
            try {
                return servletContext.getResource("/WEB-INF/lib/" + name);
            } catch (MalformedURLException e) {
                throw new RuntimeException("An error occurred while loading dependency " + name, e);
            }
        }).toArray(URL[]::new);
        URLClassLoader coreClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader);

        Thread.currentThread().setContextClassLoader(coreClassLoader);
        Class<?> appContextLoaderClass = coreClassLoader.loadClass(getAppContextLoaderClassName());
        appContextLoader = appContextLoaderClass.newInstance();

        Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames",
                String.class);
        ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile);

        Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass,
                "contextInitialized", ServletContextEvent.class);
        ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce);

        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("An error occurred while starting single WAR application", e);
    }
}

From source file:org.impalaframework.extension.mvc.annotation.handler.ServletHandlerMethodInvoker.java

private Object invokeMethod(Object handler, Method handlerMethod, NativeWebRequest webRequest,
        ExtendedModelMap implicitModel, TypeConverter typeConverter) {

    ArgumentCollector[] collection = argumentCollectors.get(handlerMethod);
    if (collection == null) {
        collection = assembleArgumentCollectors(handlerMethod, handler, webRequest, implicitModel);
    }/* w w w. ja  v a 2  s .  c o m*/

    Class<?>[] parameterTypes = handlerMethod.getParameterTypes();
    Object[] arguments = new Object[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        arguments[i] = collection[i].getArgument(webRequest, implicitModel, typeConverter);
    }

    return ReflectionUtils.invokeMethod(handlerMethod, handler, arguments);
}

From source file:org.shredzone.cilla.web.fragment.manager.FragmentInvoker.java

/**
 * Invokes the fragment renderer.//from  w  w w.j  av a  2 s.c om
 *
 * @param context
 *            {@link FragmentContext} containing all necessary data for invoking
 * @return Fragment string returned by the renderer. May be {@code null}.
 */
public String invoke(FragmentContext context) throws CillaServiceException {
    if (context == null) {
        throw new NullPointerException("context must not be null");
    }

    Class<?>[] types = method.getParameterTypes();
    Object[] values = new Object[types.length];

    for (int ix = 0; ix < types.length; ix++) {
        values[ix] = evaluateParameter(types[ix], ix, context);
    }

    Object html = ReflectionUtils.invokeMethod(method, bean, values);

    if (html != null && html instanceof CharSequence) {
        // Method returned a char sequence
        return html.toString();
    }

    if (template != null) {
        try {
            // A JSP template is defined for rendering
            context.include(template);
        } catch (IOException ex) {
            throw new CillaServiceException("Could not invoke template " + template, ex);
        }
    }

    // Renderer returned nothing, it may have written its content itself
    return null;
}

From source file:com.haulmont.cuba.core.sys.singleapp.SingleAppCoreServletListener.java

@Override
public void contextDestroyed(ServletContextEvent sce) {
    Method contextInitialized = ReflectionUtils.findMethod(appContextLoader.getClass(), "contextDestroyed",
            ServletContextEvent.class);
    ReflectionUtils.invokeMethod(contextInitialized, appContextLoader, sce);
}

From source file:org.shredzone.commons.view.manager.ViewInvoker.java

/**
 * Invokes the view handler./*from  w  w  w.j  a va2 s .  com*/
 *
 * @param context
 *            {@link ViewContext} containing all necessary data for invoking the view
 * @return String returned by the view handler. Usually this is a reference to a JSP
 *         that is used for rendering the result. If {@code null}, the view handler
 *         took care for sending a response itself.
 */
public String invoke(ViewContext context) throws ViewException {
    Class<?>[] types = method.getParameterTypes();
    Object[] values = new Object[types.length];

    for (int ix = 0; ix < types.length; ix++) {
        Object result = evaluateParameter(types[ix], viewAnnotations[ix], optionals[ix], context);
        if (result == null && !optionals[ix]) {
            throw new PageNotFoundException("Argument " + ix + " is required but missing.");
        }
        values[ix] = result;
    }

    try {
        Object renderViewName = ReflectionUtils.invokeMethod(method, bean, values);
        return (renderViewName != null ? renderViewName.toString() : null);
    } catch (UndeclaredThrowableException | IllegalStateException ex) {
        Throwable cause = ex.getCause();
        if (cause instanceof ViewException) {
            throw (ViewException) cause;
        } else {
            throw ex;
        }
    }
}

From source file:org.shredzone.cilla.plugin.social.manager.SocialHandlerInvoker.java

/**
 * Invokes the {@link SocialHandler}'s {@link SocialBookmark} method.
 *
 * @param page/*w w w  .j  av a 2s  . c  o m*/
 *            {@link Page} to create a {@link SocialLink} for
 * @return {@link SocialLink} that was created
 */
public SocialLink invoke(Page page) {
    Class<?>[] types = method.getParameterTypes();
    Object[] values = new Object[types.length];

    PageData data = new PageData(page);

    for (int ix = 0; ix < types.length; ix++) {
        values[ix] = evaluateParameter(types[ix], methodAnnotations[ix], data);
    }

    Object result = ReflectionUtils.invokeMethod(method, bean, values);

    if (result == null) {
        return null;
    } else if (result instanceof SocialLink) {
        return (SocialLink) result;
    } else if (result instanceof String) {
        String iconUrl = linkService.linkTo().view("resource").param("package", "social").param("name", icon)
                .toString();
        return new SocialLink(result.toString(), iconUrl, name);
    } else {
        throw new IllegalArgumentException("Unknown result type " + result.getClass());
    }
}