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.dspace.app.rest.utils.RestRepositoryUtils.java

public Object invokeQueryMethod(DSpaceRestRepository repository, Method method,
        MultiValueMap<String, ? extends Object> parameters, Pageable pageable, Sort sort) {

    Assert.notNull(method, "Method must not be null!");
    Assert.notNull(parameters, "Parameters must not be null!");

    ReflectionUtils.makeAccessible(method);

    return ReflectionUtils.invokeMethod(method, repository,
            prepareParameters(method, parameters, pageable, sort));
}

From source file:org.entando.entando.plugins.jpehcache.aps.system.services.EhCacheManagerFactoryBean.java

@Override
public void afterPropertiesSet() throws IOException, CacheException {
    logger.info("Initializing EhCache CacheManager");
    InputStream is = this.extractEntandoConfig();
    try {/*from  ww w  . j av  a2 s. c om*/
        // A bit convoluted for EhCache 1.x/2.0 compatibility.
        // To be much simpler once we require EhCache 2.1+
        if (this.cacheManagerName != null) {
            if (this.shared && createWithConfiguration == null) {
                // No CacheManager.create(Configuration) method available before EhCache 2.1;
                // can only set CacheManager name after creation.
                this.cacheManager = (is != null ? CacheManager.create(is) : CacheManager.create());
                this.cacheManager.setName(this.cacheManagerName);
            } else {
                Configuration configuration = (is != null ? ConfigurationFactory.parseConfiguration(is)
                        : ConfigurationFactory.parseConfiguration());
                configuration.setName(this.cacheManagerName);
                if (this.shared) {
                    this.cacheManager = (CacheManager) ReflectionUtils.invokeMethod(createWithConfiguration,
                            null, configuration);
                } else {
                    this.cacheManager = new CacheManager(configuration);
                }
            }
        } else if (this.shared) {
            // For strict backwards compatibility: use simplest possible constructors...
            this.cacheManager = (is != null ? CacheManager.create(is) : CacheManager.create());
        } else {
            this.cacheManager = (is != null ? new CacheManager(is) : new CacheManager());
        }
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.focusns.common.event.support.EventListener.java

public void onApplicationEvent(EventContext eventContext) {
    ///*from  ww w. j av a  2  s  . c om*/
    Event event = eventContext.getEventHandler().getAnnotation(Event.class);
    //
    log.debug(String.format("Event %s triggered!", event.on()));
    // invoke event handle method
    Object eventSubscriber = eventContext.getEventSubscriber();
    Method eventHandler = eventContext.getEventHandler();
    ReflectionUtils.invokeMethod(eventHandler, eventSubscriber, eventContext);
}

From source file:org.kuali.student.common.spring.WebServiceAwareSpringBeanPostProcessor.java

private void injectServiceReference(Object bean, String beanName, Field field, Object service, String message)
        throws IllegalArgumentException, IllegalAccessException {

    String fieldName = field.getName();

    String setterMethodName = "set" + StringUtils.capitalize(fieldName);

    Class<? extends Object> beanClass = bean.getClass();

    Class<?> fieldType = field.getType();

    try {/*from   w w w  .j ava  2  s  .co  m*/

        /*
         * We use the set method because even though we can reach in and set the bean
         * if it is final we still get an exception.
         * This way it will always work.
         * And since the bean's are presently being wired using XML the setters will exist.
         * 
         */
        Method setterMethod = beanClass.getMethod(setterMethodName, field.getType());

        ReflectionUtils.invokeMethod(setterMethod, bean, service);

        log.warn("RESOLVED: beanName = " + beanName + ", fieldName = " + field.getName() + ", fieldType = "
                + fieldType.getName() + message);

    } catch (IllegalArgumentException e) {
        log.warn("set error", e);
    } catch (SecurityException e) {
        log.warn("set error", e);
    } catch (NoSuchMethodException e) {

        // try the field
        ReflectionUtils.makeAccessible(field);

        field.set(bean, service);
        log.warn("RESOLVED: beanName = " + beanName + ", fieldName = " + field.getName() + ", fieldType = "
                + fieldType.getName() + message);
    }

}

From source file:org.sakaiproject.memory.impl.SakaiCacheManagerFactoryBean.java

/**
 * This is the init method/*from ww w. j  a v a2  s  .c  o m*/
 * If using Terracotta, enable caching via sakai.properties and ensure the Terracotta server is reachable
 * Use '-Dcom.tc.tc.config.total.timeout=10000' to specify how long we should try to connect to the TC server
 */
public void afterPropertiesSet() throws IOException {
    logger.info("Initializing EhCache CacheManager");
    InputStream is = (this.configLocation != null ? this.configLocation.getInputStream() : null);
    if (this.cacheEnabled == null) {
        this.cacheEnabled = serverConfigurationService.getBoolean("memory.cluster.enabled", false);
    }

    try {
        Configuration configuration = (is != null) ? ConfigurationFactory.parseConfiguration(is)
                : ConfigurationFactory.parseConfiguration();
        configuration.setName(this.cacheManagerName);
        // force the sizeof calculations to not generate lots of warnings OR degrade server performance
        configuration.getSizeOfPolicyConfiguration()
                .maxDepthExceededBehavior(SizeOfPolicyConfiguration.MaxDepthExceededBehavior.ABORT);
        configuration.getSizeOfPolicyConfiguration().maxDepth(100);

        // Setup the Terracotta cluster config
        TerracottaClientConfiguration terracottaConfig = new TerracottaClientConfiguration();

        // use Terracotta server if running and available
        if (this.cacheEnabled) {
            logger.info("Attempting to load cluster caching using Terracotta at: " + serverConfigurationService
                    .getString("memory.cluster.server.urls", DEFAULT_CACHE_SERVER_URL) + ".");
            // set the URL to the server
            String[] serverUrls = serverConfigurationService.getStrings("memory.cluster.server.urls");
            // create comma-separated string of URLs
            String serverUrlsString = StringUtils.join(serverUrls, ",");
            terracottaConfig.setUrl(serverUrlsString);
            terracottaConfig.setRejoin(true);
            configuration.addTerracottaConfig(terracottaConfig);

            // retrieve the names of all caches that will be managed by Terracotta and create cache configurations for them
            String[] caches = serverConfigurationService.getStrings("memory.cluster.names");
            if (ArrayUtils.isNotEmpty(caches)) {
                for (String cacheName : caches) {
                    CacheConfiguration cacheConfiguration = this.createClusterCacheConfiguration(cacheName);
                    if (cacheConfiguration != null) {
                        configuration.addCache(cacheConfiguration);
                    }
                }
            }

            // create new cache manager with the above configuration
            if (this.shared) {
                this.cacheManager = (CacheManager) ReflectionUtils.invokeMethod(createWithConfiguration, null,
                        configuration);
            } else {
                this.cacheManager = new CacheManager(configuration);
            }
        } else {
            // This block contains the original code from org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java
            // A bit convoluted for EhCache 1.x/2.0 compatibility.
            // To be much simpler once we require EhCache 2.1+
            logger.info("Attempting to load default cluster caching.");
            configuration.addTerracottaConfig(terracottaConfig);
            if (this.cacheManagerName != null) {
                if (this.shared && createWithConfiguration == null) {
                    // No CacheManager.create(Configuration) method available before EhCache 2.1;
                    // can only set CacheManager name after creation.
                    this.cacheManager = (is != null ? CacheManager.create(is) : CacheManager.create());
                    this.cacheManager.setName(this.cacheManagerName);
                } else {
                    configuration.setName(this.cacheManagerName);
                    if (this.shared) {
                        this.cacheManager = (CacheManager) ReflectionUtils.invokeMethod(createWithConfiguration,
                                null, configuration);
                    } else {
                        this.cacheManager = new CacheManager(configuration);
                    }
                }
            } else if (this.shared) {
                // For strict backwards compatibility: use simplest possible constructors...
                this.cacheManager = (is != null ? CacheManager.create(is) : CacheManager.create());
            } else {
                this.cacheManager = (is != null ? new CacheManager(is) : new CacheManager());
            }
        }
    } catch (CacheException ce) {
        // this is thrown if we can't connect to the Terracotta server on initialization
        if (this.cacheEnabled && this.cacheManager == null) {
            logger.error(
                    "You have cluster caching enabled in sakai.properties, but do not have a Terracotta server running at "
                            + serverConfigurationService.getString("memory.cluster.server.urls",
                                    DEFAULT_CACHE_SERVER_URL)
                            + ". Please ensure the server is running and available.",
                    ce);
            // use the default cache instead
            this.cacheEnabled = false;
            afterPropertiesSet();
        } else {
            logger.error("An error occurred while creating the cache manager: ", ce);
        }
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.shept.org.springframework.web.servlet.mvc.support.ModelUtils.java

/**
 * //from   w  w  w.ja  v  a 2 s.  c  o m
 * @return the initialize(sourceObject) a target object from a source
 */
public static void initialize(Object target, Object sourceModel) {
    if (sourceModel == null) {
        return;
    }
    Assert.notNull(target, "The object being initialized with '" + sourceModel + "' (of class '"
            + sourceModel.getClass() + "') may not be null");
    Method mth = ReflectionUtils.findMethod(target.getClass(), initMethod, sourceModel.getClass());
    if (mth == null) {
        String message = "The object of class '" + target.getClass() + "' cannot be initialized from model '"
                + sourceModel.getClass() + "' Method '" + initMethod + "(" + sourceModel.getClass()
                + ")' is missing";
        if (sourceModel instanceof String) {
            logger.info(message);
        } else {
            logger.warn(message);
        }
    } else {
        // void initialize(sourceObject)
        ReflectionUtils.invokeMethod(mth, target, sourceModel);
    }
}

From source file:org.springframework.core.io.support.PathMatchingResourcePatternResolver.java

/**
 * Find all resources that match the given location pattern via the
 * Ant-style PathMatcher. Supports resources in jar files and zip files
 * and in the file system.//from   w  w w . j av  a 2 s  . com
 * @param locationPattern the location pattern to match
 * @return the result as Resource array
 * @throws IOException in case of I/O errors
 * @see #doFindPathMatchingJarResources
 * @see #doFindPathMatchingFileResources
 * @see org.springframework.util.PathMatcher
 */
protected Resource[] findPathMatchingResources(String locationPattern) throws IOException {
    String rootDirPath = determineRootDir(locationPattern);
    String subPattern = locationPattern.substring(rootDirPath.length());
    Resource[] rootDirResources = getResources(rootDirPath);
    Set<Resource> result = new LinkedHashSet<>(16);
    for (Resource rootDirResource : rootDirResources) {
        rootDirResource = resolveRootDirResource(rootDirResource);
        URL rootDirUrl = rootDirResource.getURL();
        if (equinoxResolveMethod != null) {
            if (rootDirUrl.getProtocol().startsWith("bundle")) {
                URL resolvedUrl = (URL) ReflectionUtils.invokeMethod(equinoxResolveMethod, null, rootDirUrl);
                if (resolvedUrl != null) {
                    rootDirUrl = resolvedUrl;
                }
                rootDirResource = new UrlResource(rootDirUrl);
            }
        }
        if (rootDirUrl.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) {
            result.addAll(VfsResourceMatchingDelegate.findMatchingResources(rootDirUrl, subPattern,
                    getPathMatcher()));
        } else if (ResourceUtils.isJarURL(rootDirUrl) || isJarResource(rootDirResource)) {
            result.addAll(doFindPathMatchingJarResources(rootDirResource, rootDirUrl, subPattern));
        } else {
            result.addAll(doFindPathMatchingFileResources(rootDirResource, subPattern));
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resolved location pattern [" + locationPattern + "] to resources " + result);
    }
    return result.toArray(new Resource[result.size()]);
}

From source file:org.springframework.data.gemfire.function.PojoFunctionWrapper.java

protected final Object invokeTargetMethod(Object[] args) {
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("about to invoke method %s on class %s as function %s", method.getName(),
                target.getClass().getName(), this.id));

        for (Object arg : args) {
            logger.debug("arg:" + arg.getClass().getName() + " " + arg.toString());
        }/* w w  w  .j a va 2  s  .  co m*/
    }

    return ReflectionUtils.invokeMethod(method, target, (Object[]) args);
}

From source file:org.springframework.data.hadoop.pig.PigUtils.java

static void validateEachStatement(PigServer pig, boolean validate) {
    Method validateMethod = ReflectionUtils.findMethod(PigServer.class, "setValidateEachStatement",
            boolean.class);
    if (validateMethod != null) {
        ReflectionUtils.invokeMethod(validateMethod, pig, validate);
    }//ww  w . ja  v a 2  s  .c  om
}

From source file:org.springframework.flex.core.MessageBrokerFactoryBean.java

private void setInitServletContext() {

    // This is undesirable but necessary at the moment for LCDS to be able to load its license configuration.
    // Hopefully we can get the BlazeDS/LCDS team to give us a better option in the future.
    Method initMethod = ReflectionUtils.findMethod(MessageBroker.class, "setServletContext",
            new Class[] { ServletContext.class });
    if (initMethod == null) {
        initMethod = ReflectionUtils.findMethod(MessageBroker.class, "setInitServletContext",
                new Class[] { ServletContext.class });
    }/*from  w ww  . jav a2 s. c  om*/
    ReflectionUtils.makeAccessible(initMethod);
    ReflectionUtils.invokeMethod(initMethod, this.messageBroker, new Object[] { this.servletContext });
}