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) 

Source Link

Document

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

Usage

From source file:org.grails.datastore.mapping.query.order.ManualEntityOrdering.java

public List applyOrder(List results, Query.Order order) {
    final String name = order.getProperty();

    @SuppressWarnings("hiding")
    final PersistentEntity entity = getEntity();
    PersistentProperty property = entity.getPropertyByName(name);
    if (property == null) {
        final PersistentProperty identity = entity.getIdentity();
        if (name.equals(identity.getName())) {
            property = identity;// w  ww.  j ava2 s .  c o  m
        }
    }

    if (property != null) {
        final PersistentProperty finalProperty = property;
        Collections.sort(results, new Comparator() {

            public int compare(Object o1, Object o2) {

                if (entity.isInstance(o1) && entity.isInstance(o2)) {
                    final String propertyName = finalProperty.getName();
                    Method readMethod = cachedReadMethods.get(propertyName);
                    if (readMethod == null) {
                        BeanWrapper b = PropertyAccessorFactory.forBeanPropertyAccess(o1);
                        final PropertyDescriptor pd = b.getPropertyDescriptor(propertyName);
                        if (pd != null) {
                            readMethod = pd.getReadMethod();
                            if (readMethod != null) {
                                ReflectionUtils.makeAccessible(readMethod);
                                cachedReadMethods.put(propertyName, readMethod);
                            }
                        }
                    }

                    if (readMethod != null) {
                        final Class<?> declaringClass = readMethod.getDeclaringClass();
                        if (declaringClass.isInstance(o1) && declaringClass.isInstance(o2)) {
                            Object left = ReflectionUtils.invokeMethod(readMethod, o1);
                            Object right = ReflectionUtils.invokeMethod(readMethod, o2);

                            if (left == null && right == null)
                                return 0;
                            if (left != null && right == null)
                                return 1;
                            if (left == null)
                                return -1;
                            if ((left instanceof Comparable) && (right instanceof Comparable)) {
                                return ((Comparable) left).compareTo(right);
                            }
                        }
                    }
                }
                return 0;
            }
        });
    }

    if (order.getDirection() == Query.Order.Direction.DESC) {
        results = reverse(results);
    }

    return results;
}

From source file:org.socialsignin.spring.data.dynamodb.repository.support.FieldAndGetterReflectionEntityInformation.java

@SuppressWarnings("unchecked")
public ID getId(T entity) {
    if (method != null) {
        return entity == null ? null : (ID) ReflectionUtils.invokeMethod(method, entity);
    } else {//from  w  ww. j av  a  2s. co  m
        return entity == null ? null : (ID) ReflectionUtils.getField(field, entity);
    }
}

From source file:org.reusables.access.AbstractHibernateRepository.java

/**
 * @return The currect session./*from   w ww .  jav a  2  s .c o m*/
 * @since 1.2.0
 */
protected Session getSession() {
    return (Session) ReflectionUtils.invokeMethod(getCurrentSessionMethod, this.sessionFactory);
}

From source file:org.focusns.common.validation.ValidationHelper.java

/**
 * ??/*  w w  w  .  j a v  a 2  s. c  om*/
 * 
 * @param constraintDescriptor
 * @return
 */
private static List<String> getConstraintParams(ConstraintDescriptor<?> constraintDescriptor) {
    Annotation constraintInstance = constraintDescriptor.getAnnotation();
    Class<?> constraintClass = constraintDescriptor.getAnnotation().annotationType();
    //
    List<String> params = new ArrayList<String>();
    //
    Method valueMethod = ClassUtils.getMethodIfAvailable(constraintClass, "value", (Class<?>[]) null);
    if (valueMethod != null) {
        String value = String.valueOf(ReflectionUtils.invokeMethod(valueMethod, constraintInstance));
        params.add("value:" + value);
    }
    Map<String, Object> annotationAttrs = AnnotationUtils.getAnnotationAttributes(constraintInstance);
    for (String key : annotationAttrs.keySet()) {
        if ("message".equals(key) || "payload".equals(key)) {
            continue;
        }
        //
        String value = "";
        if ("groups".equals(key)) {
            List<String> groupNames = new ArrayList<String>();
            Class[] groupClasses = (Class[]) annotationAttrs.get(key);
            for (Class groupClass : groupClasses) {
                groupNames.add(groupClass.getName());
            }
            value = StringUtils.collectionToDelimitedString(groupNames, "|");
        } else {
            value = String.valueOf(annotationAttrs.get(key));
        }
        //
        if (StringUtils.hasText(value)) {
            params.add(key + ":" + "'" + value + "'");
        }
    }
    //
    return params;
}

From source file:reactor.spring.context.ConsumerBeanPostProcessor.java

@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
        @Override/*  ww  w.  j a  v  a  2 s  .c om*/
        public void doWith(final Method method) throws IllegalArgumentException, IllegalAccessException {
            Annotation anno = AnnotationUtils.findAnnotation(method, On.class);
            if (null == anno) {
                return;
            }

            StandardEvaluationContext evalCtx = new StandardEvaluationContext();
            evalCtx.setRootObject(bean);
            evalCtx.setBeanResolver(beanResolver);
            evalCtx.setMethodResolvers(METHOD_RESOLVERS);

            On onAnno = (On) anno;

            Object reactorObj = null;
            if (StringUtils.hasText(onAnno.reactor())) {
                Expression reactorExpr = expressionParser.parseExpression(onAnno.reactor());
                reactorObj = reactorExpr.getValue(evalCtx);
            }

            Object selObj;
            if (StringUtils.hasText(onAnno.selector())) {
                try {
                    Expression selectorExpr = expressionParser.parseExpression(onAnno.selector());
                    selObj = selectorExpr.getValue(evalCtx);
                } catch (EvaluationException e) {
                    selObj = Fn.$(onAnno.selector());
                }
            } else {
                selObj = Fn.$(method.getName());
            }

            Consumer<Event<Object>> handler = new Consumer<Event<Object>>() {
                Class<?>[] argTypes = method.getParameterTypes();

                @Override
                public void accept(Event<Object> ev) {
                    if (argTypes.length == 0) {
                        ReflectionUtils.invokeMethod(method, bean);
                        return;
                    }

                    if (!argTypes[0].isAssignableFrom(ev.getClass())
                            && conversionService.canConvert(ev.getClass(), argTypes[0])) {
                        ReflectionUtils.invokeMethod(method, bean, conversionService.convert(ev, argTypes[0]));
                    } else {
                        ReflectionUtils.invokeMethod(method, bean, ev);
                        return;
                    }

                    if (null == ev.getData() || argTypes[0].isAssignableFrom(ev.getData().getClass())) {
                        ReflectionUtils.invokeMethod(method, bean, ev.getData());
                        return;
                    }

                    if (conversionService.canConvert(ev.getData().getClass(), argTypes[0])) {
                        ReflectionUtils.invokeMethod(method, bean,
                                conversionService.convert(ev.getData(), argTypes[0]));
                        return;
                    }

                    throw new IllegalArgumentException(
                            "Cannot invoke method " + method + " passing parameter " + ev.getData());
                }
            };

            if (!(selObj instanceof Selector)) {
                throw new IllegalArgumentException(selObj + ", referred to by the expression '"
                        + onAnno.selector() + "', is not a Selector");
            }
            if (null == reactorObj) {
                throw new IllegalStateException("Cannot register handler with null Reactor");
            } else {
                ((Reactor) reactorObj).on((Selector) selObj, handler);
            }
        }
    });
    return bean;
}

From source file:com.frank.search.solr.server.support.SolrClientUtils.java

private static SolrClient cloneHttpSolrClient(SolrClient solrClient, String core) {
    if (solrClient == null) {
        return null;
    }//from   w  w  w  .  j  av  a  2s . c o m

    Method baseUrlGetterMethod = ClassUtils.getMethodIfAvailable(solrClient.getClass(), "getBaseURL");
    if (baseUrlGetterMethod == null) {
        return null;
    }

    String baseUrl = (String) ReflectionUtils.invokeMethod(baseUrlGetterMethod, solrClient);
    String url = appendCoreToBaseUrl(baseUrl, core);

    try {

        HttpClient clientToUse = readAndCloneHttpClient(solrClient);

        if (clientToUse != null) {
            Constructor<? extends SolrClient> constructor = (Constructor<? extends SolrClient>) ClassUtils
                    .getConstructorIfAvailable(solrClient.getClass(), String.class, HttpClient.class);
            if (constructor != null) {
                return (SolrClient) BeanUtils.instantiateClass(constructor, url, clientToUse);
            }
        }

        Constructor<? extends SolrClient> constructor = (Constructor<? extends SolrClient>) ClassUtils
                .getConstructorIfAvailable(solrClient.getClass(), String.class);
        return (SolrClient) BeanUtils.instantiateClass(constructor, url);
    } catch (Exception e) {
        throw new BeanInstantiationException(solrClient.getClass(),
                "Cannot create instace of " + solrClient.getClass() + ". ", e);
    }
}

From source file:ch.qos.logback.ext.spring.web.WebLogbackConfigurer.java

/**
 * Initialize Logback, including setting the web app root system property.
 *
 * @param servletContext the current ServletContext
 * @see org.springframework.web.util.WebUtils#setWebAppRootSystemProperty
 *///from w ww .  j  a v  a2 s.  co  m
public static void initLogging(ServletContext servletContext) {
    // Expose the web app root system property.
    if (exposeWebAppRoot(servletContext)) {
        WebUtils.setWebAppRootSystemProperty(servletContext);
    }

    // Only perform custom Logback initialization in case of a config file.
    String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
    if (location != null) {
        // Perform actual Logback initialization; else rely on Logback's default initialization.
        try {
            // Resolve system property placeholders before potentially resolving real path.
            location = ServletContextPropertyUtils.resolvePlaceholders(location);
            // Return a URL (e.g. "classpath:" or "file:") as-is;
            // consider a plain file path as relative to the web application root directory.
            if (!ResourceUtils.isUrl(location)) {
                location = WebUtils.getRealPath(servletContext, location);
            }

            // Write log message to server log.
            servletContext.log("Initializing Logback from [" + location + "]");

            // Initialize
            LogbackConfigurer.initLogging(location);
        } catch (FileNotFoundException ex) {
            throw new IllegalArgumentException("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage());
        } catch (JoranException e) {
            throw new RuntimeException("Unexpected error while configuring logback", e);
        }
    }

    //If SLF4J's java.util.logging bridge is available in the classpath, install it. This will direct any messages
    //from the Java Logging framework into SLF4J. When logging is terminated, the bridge will need to be uninstalled
    try {
        Class<?> julBridge = ClassUtils.forName("org.slf4j.bridge.SLF4JBridgeHandler",
                ClassUtils.getDefaultClassLoader());

        Method removeHandlers = ReflectionUtils.findMethod(julBridge, "removeHandlersForRootLogger");
        if (removeHandlers != null) {
            servletContext.log("Removing all previous handlers for JUL to SLF4J bridge");
            ReflectionUtils.invokeMethod(removeHandlers, null);
        }

        Method install = ReflectionUtils.findMethod(julBridge, "install");
        if (install != null) {
            servletContext.log("Installing JUL to SLF4J bridge");
            ReflectionUtils.invokeMethod(install, null);
        }
    } catch (ClassNotFoundException ignored) {
        //Indicates the java.util.logging bridge is not in the classpath. This is not an indication of a problem.
        servletContext.log("JUL to SLF4J bridge is not available on the classpath");
    }
}

From source file:org.grails.datastore.gorm.events.DomainEventListener.java

private boolean invokeEvent(String eventName, PersistentEntity entity, EntityAccess ea) {
    final Map<String, Method> events = entityEvents.get(entity);
    if (events == null) {
        return true;
    }/* w w w . j  ava2s.  co  m*/

    final Method eventMethod = events.get(eventName);
    if (eventMethod == null) {
        return true;
    }

    final Object result = ReflectionUtils.invokeMethod(eventMethod, ea.getEntity());
    boolean booleanResult = (result instanceof Boolean) ? (Boolean) result : true;
    if (booleanResult && REFRESH_EVENTS.contains(eventName)) {
        ea.refresh();
    }
    return booleanResult;
}

From source file:net.paslavsky.springrest.SpringAnnotationPreprocessor.java

private String getValue(Annotation[] annotations, Class<? extends Annotation> annotationClass) {
    for (Annotation annotation : annotations) {
        if (annotationClass.isInstance(annotation)) {
            Method valueMethod = ReflectionUtils.findMethod(annotationClass, "value");
            if (valueMethod != null) {
                return (String) ReflectionUtils.invokeMethod(valueMethod, annotation);
            } else {
                return null;
            }//w w  w.  ja  v a 2s .  co  m
        }
    }

    return null;
}

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

private static Serializable getIdValue_old(DaoSupport dao, Object model) {
    checkProvider(dao);/*  w  ww  . j a  v a 2  s  .co m*/
    String idStr = getIdentifierPropertyName_old(dao, model);
    if (!(StringUtils.hasText(idStr))) {
        return null;
    }
    Method idMth = ReflectionUtils.findMethod(model.getClass(), "get" + StringUtils.capitalize(idStr));
    Serializable idxObj = (Serializable) ReflectionUtils.invokeMethod(idMth, model);
    return idxObj;
}