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.socialsignin.spring.data.dynamodb.repository.support.DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl.java

public T getHashKeyPropotypeEntityForHashKey(Object hashKey) {

    try {/* w  w w  .  j  a  v  a2s .  c  o m*/
        T entity = getJavaType().newInstance();
        if (hashKeySetterMethod != null) {
            ReflectionUtils.invokeMethod(hashKeySetterMethod, entity, hashKey);
        } else {
            ReflectionUtils.setField(hashKeyField, entity, hashKey);
        }

        return entity;
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.alpha.velocity.spring.web.VelocityToolboxView.java

/**
 * Overridden to check for the ViewContext interface which is part of the
 * view package of Velocity Tools. This requires a special Velocity context,
 * like ChainedContext as set up by {@link #createVelocityContext} in this class.
 *//* w ww. j a  v  a  2 s.  co m*/
@Override
protected void initTool(Object tool, Context velocityContext) throws Exception {
    // Velocity Tools 1.3: a class-level "init(Object)" method.
    Method initMethod = ClassUtils.getMethodIfAvailable(tool.getClass(), "init", Object.class);
    if (initMethod != null) {
        ReflectionUtils.invokeMethod(initMethod, tool, velocityContext);
    }
}

From source file:com.expedia.seiso.web.controller.delegate.RepoSearchDelegate.java

private Object getResult(Class<?> itemClass, Method searchMethod, Pageable pageable,
        MultiValueMap<String, String> params) {

    val searchMethodName = searchMethod.getName();
    log.trace("Finding {} using method {}", itemClass.getSimpleName(), searchMethodName);
    val repo = repositories.getRepositoryFor(itemClass);
    val paramClasses = searchMethod.getParameterTypes();
    val allAnns = searchMethod.getParameterAnnotations();
    val paramVals = new Object[paramClasses.length];

    for (int i = 0; i < paramClasses.length; i++) {
        log.trace("Processing param {}", i);
        if (paramClasses[i] == Pageable.class) {
            paramVals[i] = pageable;/* w w  w  .  j a  v a 2 s.c  om*/
        } else {
            val currentAnns = allAnns[i];
            for (val currentAnn : currentAnns) {
                if (Param.class.equals(currentAnn.annotationType())) {
                    log.trace("Found @Param");
                    if (conversionService.canConvert(String.class, paramClasses[i])) {
                        val paramAnn = (Param) currentAnn;
                        val paramName = paramAnn.value();
                        val paramValAsStr = params.getFirst(paramName);
                        log.trace("Setting param: {}={}", paramName, paramValAsStr);
                        paramVals[i] = conversionService.convert(paramValAsStr, paramClasses[i]);
                    } else {
                        log.trace("BUG! Not setting the param value!");
                    }
                }
            }
        }
    }

    log.trace("Invoking {}.{} with {} params", repo.getClass().getName(), searchMethodName, paramVals.length);
    return ReflectionUtils.invokeMethod(searchMethod, repo, paramVals);
}

From source file:org.synyx.hera.si.PluginRegistryAwareMessageHandler.java

private List<Object> invokePlugins(Collection<? extends Plugin<?>> plugins, Message<?> message) {
    List<Object> results = new ArrayList<Object>();
    if (LOG.isDebugEnabled()) {
        LOG.debug(String.format("Invoking plugin(s) %s with message %s",
                StringUtils.collectionToCommaDelimitedString(plugins), message));
    }//w  w w .j  a va 2  s.co m

    for (Plugin<?> plugin : plugins) {

        Object[] invocationArguments = getInvocationArguments(message);
        Class<?>[] types = getTypes(invocationArguments);

        Method businessMethod = ReflectionUtils.findMethod(pluginType, serviceMethodName, types);

        if (businessMethod == null) {
            throw new MessageHandlingException(message,
                    String.format("Did not find a method %s on %s taking the following parameters %s",
                            serviceMethodName, pluginType.getName(), Arrays.toString(types)));
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Invoke plugin method %s using arguments %s", businessMethod,
                    Arrays.toString(invocationArguments)));
        }

        Object result = ReflectionUtils.invokeMethod(businessMethod, plugin, invocationArguments);

        if (!businessMethod.getReturnType().equals(void.class)) {
            results.add(result);
        }
    }

    return results;
}

From source file:com.aol.advertising.qiao.util.ContextUtils.java

public static void injectMethods(Object object, Map<String, PropertyValue> props)
        throws BeansException, ClassNotFoundException {
    resolvePropertyReferences(props);//from w  w  w.jav  a2 s .  c  o m

    if (props != null) {
        for (String key : props.keySet()) {
            String mth_name = "set" + StringUtils.capitalize(key);

            PropertyValue pv = props.get(key);
            if (pv.getType() == Type.IS_VALUE) {
                String pv_value = pv.getValue();
                if (!pv.isResolved()) {
                    if (pv.getDefaultValue() == null) // not resolved + no default
                        throw new ConfigurationException("value " + pv.getValue() + " not resolved");

                    pv_value = pv.getDefaultValue();
                }

                Method mth = findMethod(object.getClass(), mth_name, pv.getDataType().getJavaClass());
                if (mth != null) {
                    ReflectionUtils.invokeMethod(mth, object,
                            ContextUtils.stringToValueByType(pv_value, pv.getDataType()));
                } else {
                    String err = String.format(ERR_METHOD_NOTFOUND, mth_name, pv.getDataType(),
                            object.getClass().getSimpleName());
                    logger.error(err);
                    throw new MethodNotFoundException(err);

                }
            } else {
                Method mth = findMethod(object.getClass(), mth_name, pv.getRefObject().getClass());

                if (mth != null) {
                    ReflectionUtils.invokeMethod(mth, object, pv.getRefObject());
                } else {
                    String err = String.format(ERR_METHOD_NOTFOUND, mth_name,
                            pv.getRefObject().getClass().getSimpleName(), object.getClass().getSimpleName());
                    logger.error(err);
                    throw new MethodNotFoundException(err);
                }
            }
        }
    }
}

From source file:org.shept.persistence.provider.DaoUtils.java

private static Object copyTemplate_Experimental(HibernateDaoSupport dao, Object entityModelTemplate) {
    ClassMetadata modelMeta = getClassMetadata(dao, entityModelTemplate);
    if (null == modelMeta) {
        return null;
    }//from  w  ww .ja  v  a2 s  . c  o  m
    String idName = modelMeta.getIdentifierPropertyName();
    Object modelCopy = BeanUtils.instantiateClass(entityModelTemplate.getClass());
    BeanUtils.copyProperties(entityModelTemplate, modelCopy, new String[] { idName });

    Type idType = modelMeta.getIdentifierType();
    if (null == idType || !idType.isComponentType()) {
        return modelCopy;
    }

    Object idValue = modelMeta.getPropertyValue(entityModelTemplate, idName, EntityMode.POJO);
    if (null == idValue) {
        return modelCopy;
    }

    Object idCopy = BeanUtils.instantiate(idValue.getClass());
    BeanUtils.copyProperties(idValue, idCopy);

    if (null == idValue || (null != idType)) {
        return modelCopy;
    }

    Method idMth = ReflectionUtils.findMethod(entityModelTemplate.getClass(),
            "set" + StringUtils.capitalize(idName), new Class[] {});
    if (idMth != null) {
        ReflectionUtils.invokeMethod(idMth, modelCopy, idCopy);
    }

    return modelCopy;
}

From source file:com.aol.advertising.qiao.util.ContextUtils.java

/**
 * A simple call to invoke a class method.
 *
 * @param object//from w ww .j a  v a2  s. c o m
 *            the target object to invoke the method on
 * @param fieldName
 *            the field whose set method to be invoked
 * @param param
 *            the invocation argument
 * @throws BeansException
 * @throws ClassNotFoundException
 */
public static void injectMethod(Object object, String fieldName, Object param)
        throws BeansException, ClassNotFoundException {
    String mth_name = "set" + StringUtils.capitalize(fieldName);

    Method mth = findMethod(object.getClass(), mth_name, param.getClass());

    if (mth != null) {
        ReflectionUtils.invokeMethod(mth, object, param);
    } else {
        String err = String.format(ERR_METHOD_NOTFOUND, mth_name, param.getClass().getSimpleName(),
                object.getClass().getSimpleName());
        logger.error(err);
        throw new MethodNotFoundException(err);
    }
}

From source file:com.drillmap.crm.repository.extensions.invoker.ReflectionRepositoryInvoker.java

/**
 * Invokes the given method with the given arguments on the backing repository.
 * //  w  ww  .  ja v a  2 s  .com
 * @param method
 * @param arguments
 * @return
 */
@SuppressWarnings("unchecked")
private <T> T invoke(Method method, Object... arguments) {
    return (T) ReflectionUtils.invokeMethod(method, repository, arguments);
}

From source file:com.aol.advertising.qiao.util.ContextUtils.java

/**
 * Invoke a class method if exists./*  w  ww  .j  av  a 2 s  . c o  m*/
 *
 * @param object
 * @param fieldName
 * @param param
 * @throws BeansException
 * @throws ClassNotFoundException
 */
public static void injectMethodSilently(Object object, String fieldName, Object param)
        throws BeansException, ClassNotFoundException {
    String mth_name = "set" + StringUtils.capitalize(fieldName);

    Method mth = findMethod(object.getClass(), mth_name, param.getClass());

    if (mth != null) {
        ReflectionUtils.invokeMethod(mth, object, param);
    }
}

From source file:org.openspaces.pu.container.jee.jetty.JettyWebApplicationContextListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    final ServletContext servletContext = servletContextEvent.getServletContext();
    // a hack to get the jetty context
    final ServletContextHandler jettyContext = (ServletContextHandler) ((ContextHandler.Context) servletContext)
            .getContextHandler();/* w  ww  . j  a  va  2  s  .  com*/
    final SessionHandler sessionHandler = jettyContext.getSessionHandler();
    BeanLevelProperties beanLevelProperties = (BeanLevelProperties) servletContext
            .getAttribute(JeeProcessingUnitContainerProvider.BEAN_LEVEL_PROPERTIES_CONTEXT);
    ClusterInfo clusterInfo = (ClusterInfo) servletContext
            .getAttribute(JeeProcessingUnitContainerProvider.CLUSTER_INFO_CONTEXT);
    if (beanLevelProperties != null) {

        // automatically enable GigaSpaces Session Manager when passing the relevant property
        String sessionsSpaceUrl = beanLevelProperties.getContextProperties().getProperty(JETTY_SESSIONS_URL);
        if (sessionsSpaceUrl != null) {
            logger.info("Jetty GigaSpaces Session support using space url [" + sessionsSpaceUrl + "]");
            GigaSessionManager gigaSessionManager = new GigaSessionManager();

            if (sessionsSpaceUrl.startsWith("bean://")) {
                ApplicationContext applicationContext = (ApplicationContext) servletContext
                        .getAttribute(JeeProcessingUnitContainerProvider.APPLICATION_CONTEXT_CONTEXT);
                if (applicationContext == null) {
                    throw new IllegalStateException("Failed to find servlet context bound application context");
                }
                GigaSpace space;
                Object bean = applicationContext.getBean(sessionsSpaceUrl.substring("bean://".length()));
                if (bean instanceof GigaSpace) {
                    space = (GigaSpace) bean;
                } else if (bean instanceof IJSpace) {
                    space = new GigaSpaceConfigurer((IJSpace) bean).create();
                } else {
                    throw new IllegalArgumentException(
                            "Bean [" + bean + "] is not of either GigaSpace type or IJSpace type");
                }
                gigaSessionManager.setSpace(space);
            } else {
                gigaSessionManager.setUrlSpaceConfigurer(
                        new UrlSpaceConfigurer(sessionsSpaceUrl).clusterInfo(clusterInfo));
            }

            String scavangePeriod = beanLevelProperties.getContextProperties()
                    .getProperty(JETTY_SESSIONS_SCAVENGE_PERIOD);
            if (scavangePeriod != null) {
                gigaSessionManager.setScavengePeriod(Integer.parseInt(scavangePeriod));
                if (logger.isDebugEnabled()) {
                    logger.debug("Setting scavenge period to [" + scavangePeriod + "] seconds");
                }
            }
            String savePeriod = beanLevelProperties.getContextProperties()
                    .getProperty(JETTY_SESSIONS_SAVE_PERIOD);
            if (savePeriod != null) {
                gigaSessionManager.setSavePeriod(Integer.parseInt(savePeriod));
                if (logger.isDebugEnabled()) {
                    logger.debug("Setting save period to [" + savePeriod + "] seconds");
                }
            }
            String lease = beanLevelProperties.getContextProperties().getProperty(JETTY_SESSIONS_LEASE);
            if (lease != null) {
                gigaSessionManager.setLease(Long.parseLong(lease));
                if (logger.isDebugEnabled()) {
                    logger.debug("Setting lease to [" + lease + "] milliseconds");
                }
            }

            // copy over session settings

            SessionManager sessionManager = sessionHandler.getSessionManager();
            gigaSessionManager.getSessionCookieConfig()
                    .setName(sessionManager.getSessionCookieConfig().getName());
            gigaSessionManager.getSessionCookieConfig()
                    .setDomain(sessionManager.getSessionCookieConfig().getDomain());
            gigaSessionManager.getSessionCookieConfig()
                    .setPath(sessionManager.getSessionCookieConfig().getPath());
            gigaSessionManager.setUsingCookies(sessionManager.isUsingCookies());
            gigaSessionManager.getSessionCookieConfig()
                    .setMaxAge(sessionManager.getSessionCookieConfig().getMaxAge());
            gigaSessionManager.getSessionCookieConfig()
                    .setSecure(sessionManager.getSessionCookieConfig().isSecure());
            gigaSessionManager.setMaxInactiveInterval(sessionManager.getMaxInactiveInterval());
            gigaSessionManager.setHttpOnly(sessionManager.getHttpOnly());
            gigaSessionManager.getSessionCookieConfig()
                    .setComment(sessionManager.getSessionCookieConfig().getComment());

            String sessionTimeout = beanLevelProperties.getContextProperties()
                    .getProperty(JETTY_SESSIONS_TIMEOUT);
            if (sessionTimeout != null) {
                gigaSessionManager.setMaxInactiveInterval(Integer.parseInt(sessionTimeout) * 60);
                if (logger.isDebugEnabled()) {
                    logger.debug("Setting session timeout to [" + sessionTimeout + "] seconds");
                }
            }

            GigaSessionIdManager sessionIdManager = new GigaSessionIdManager(jettyContext.getServer());
            sessionIdManager.setWorkerName(clusterInfo.getUniqueName().replace('.', '_'));
            gigaSessionManager.setIdManager(sessionIdManager);
            // replace the actual session manager inside the LazySessionManager with GS session manager, this is
            // because in Jetty 9 it no more possible to replace the session manager after the server started
            // without deleting all webapps.
            if ("GSLazySessionManager".equals(sessionManager.getClass().getSimpleName())) {
                try {
                    Method method = ReflectionUtils.findMethod(sessionManager.getClass(), "replaceDefault",
                            SessionManager.class);
                    if (method != null) {
                        ReflectionUtils.invokeMethod(method, sessionManager, gigaSessionManager);
                    } else {
                        throw new NoSuchMethodException("replaceDefault");
                    }
                } catch (Exception e) {
                    throw new RuntimeException(
                            "Failed to replace default session manager with GSSessionManager", e);
                }
            }
        }

        // if we have a simple hash session id manager, set its worker name automatically...
        if (sessionHandler.getSessionManager().getSessionIdManager() instanceof HashSessionIdManager) {
            HashSessionIdManager sessionIdManager = (HashSessionIdManager) sessionHandler.getSessionManager()
                    .getSessionIdManager();
            if (sessionIdManager.getWorkerName() == null) {
                final String workerName = clusterInfo.getUniqueName().replace('.', '_');
                if (logger.isDebugEnabled()) {
                    logger.debug("Automatically setting worker name to [" + workerName + "]");
                }
                stop(sessionIdManager, "to set worker name");
                sessionIdManager.setWorkerName(workerName);
                start(sessionIdManager, "to set worker name");
            }
        }
    }
}