Example usage for org.springframework.util ReflectionUtils findMethod

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

Introduction

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

Prototype

@Nullable
public static Method findMethod(Class<?> clazz, String name) 

Source Link

Document

Attempt to find a Method on the supplied class with the supplied name and no parameters.

Usage

From source file:org.codehaus.groovy.grails.orm.hibernate.support.ClosureEventListener.java

private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) {
    Method method = ReflectionUtils.findMethod(domainClazz, event);
    if (method != null) {
        ReflectionUtils.makeAccessible(method);
        return new MethodCaller(method);
    }//from   w w  w.  ja  v  a 2s  .com

    Field field = ReflectionUtils.findField(domainClazz, event);
    if (field != null) {
        ReflectionUtils.makeAccessible(field);
        return new FieldClosureCaller(field);
    }

    MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY);
    if (metaMethod != null) {
        return new MetaMethodCaller(metaMethod);
    }

    MetaProperty metaProperty = domainMetaClass.getMetaProperty(event);
    if (metaProperty != null) {
        return new MetaPropertyClosureCaller(metaProperty);
    }

    return null;
}

From source file:org.lexevs.dao.database.utility.DaoUtility.java

@SuppressWarnings("unchecked")
public static <T extends URIMap> T getURIMap(Mappings mappings, Class<T> uriMapClass, String localId) {
    if (mappings == null) {
        return null;
    }/* w w  w .  j  a v  a  2  s  .  c o m*/

    final String getPrefix = "get";
    final String getSuffix = "AsReference";

    List<T> uriMapList = (List<T>) ReflectionUtils.invokeMethod(
            ReflectionUtils.findMethod(Mappings.class, getPrefix + uriMapClass.getSimpleName() + getSuffix),
            mappings);

    List<T> returnList = new ArrayList<T>();

    for (T map : uriMapList) {
        if (map.getLocalId().equalsIgnoreCase(localId)) {
            returnList.add(map);
        }
    }

    if (CollectionUtils.isEmpty(returnList)) {
        return null;
    }

    if (returnList.size() > 1) {
        throw new IllegalStateException("Two URIMaps found with the same LocalID: " + localId);
    }

    return returnList.get(0);
}

From source file:org.openmrs.module.webservices.rest.web.resource.impl.DelegatingSubResource.java

@RepHandler(RefRepresentation.class)
public SimpleObject asRef(T delegate) throws ConversionException {
    DelegatingResourceDescription description = new DelegatingResourceDescription();
    description.addProperty("uuid");
    description.addProperty("display", findMethod("getDisplayString"));

    Method method = ReflectionUtils.findMethod(delegate.getClass(), "isVoided");

    if (method != null) {
        try {//from www .ja  v  a 2  s . c  om
            if ((Boolean) method.invoke(delegate))
                description.addProperty("voided");
        } catch (IllegalArgumentException e) {
            log.debug("unable to get voided status", e);
        } catch (IllegalAccessException e) {
            log.debug("unable to get voided status", e);
        } catch (InvocationTargetException e) {
            log.debug("unable to get voided status", e);
        }
    } else {
        // couldn't find an "isVoided" method, look for "isRetired"
        method = ReflectionUtils.findMethod(delegate.getClass(), "isRetired");
        if (method != null) {
            try {
                if ((Boolean) method.invoke(delegate))
                    description.addProperty("retired");
            } catch (IllegalArgumentException e) {
                log.debug("unable to get retired status", e);
            } catch (IllegalAccessException e) {
                log.debug("unable to get retired status", e);
            } catch (InvocationTargetException e) {
                log.debug("unable to get retired status", e);
            }
        }
    }

    description.addSelfLink();
    return convertDelegateToRepresentation(delegate, description);
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.command.AssociationCommandFactory.java

/**
 * //from ww w .  j a  v a2  s .com
 * @see org.shept.org.springframework.web.servlet.mvc.delegation.command.CommandFactory#getCommand(org.shept.org.springframework.web.servlet.mvc.delegation.ComponentConfiguration, java.lang.Object, java.lang.String)
 * 
 * @param model
 * @param jp
 * @param mth
 * @return
 */
@Override
public Object getCommand(TargetConfiguration config, Object model) {

    if (model == null) {
        throw new ChainConfigurationException("Configuration error in '" + config.getChainNameDisplay()
                + "'. <Null> model is not allowed for associations");
    }

    // param contains the subForm name that will be overriden if there is an relation defined
    String assoc = relation == null ? config.getTo().getBeanName() : relation;
    if (assoc != null && assoc.startsWith("get")) {
        assoc = relation.substring("get".length());
    }
    String methodGetter = "get" + StringUtils.capitalize(assoc);
    Method mth = ReflectionUtils.findMethod(model.getClass(), methodGetter);
    if (mth == null) {
        return null;
    }
    Class<?> rt = Object.class;
    if (null != mth) {
        rt = mth.getReturnType();
    }
    if (List.class.isAssignableFrom(rt)) {
        return createWrappedList(config, mth, model);
    }
    // TODO better checks for the different result conditions ...
    else if (Collection.class.isAssignableFrom(rt)) {
        throw new ChainConfigurationException("Collection types other than 'List' are currently not supported. "
                + "Type " + rt.getClass().toString() + " is not supported. Use List instead");
    }
    // load a single entity object
    else {
        return createWrappedEntity(config, mth, model);
    }
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.ComponentUtils.java

/**
 * //  www.  j ava 2  s.c om
 * @param
 * @return
 *
 * @param wrapper
 * @param ctx
 * @param model
 * @param selector
 * @return
 */
public static String getComponentInfo(HttpServletRequest request, InfoItem item, Object model) {
    if (item == null)
        return null;
    if (item.getCode() == null)
        return null;
    WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request);
    Locale locale = RequestContextUtils.getLocale(request);
    String arg = null;
    Method mth;
    if (model != null) {
        if (StringUtils.hasText(item.getSelector())) {
            mth = ReflectionUtils.findMethod(model.getClass(),
                    StringUtilsExtended.getReadAccessor(item.getSelector()));
            if (mth != null) {
                arg = (String) ReflectionUtils.invokeMethod(mth, model);
            }
        }
    }
    if (StringUtils.hasText(arg)) {
        return ctx.getMessage(item.getCode(), new String[] { arg }, "???", locale);
    } else {
        return ctx.getMessage(item.getCode(), null, "???", locale);
    }
}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.configuration.TargetConfiguration.java

@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
    Assert.notNull(to);//w  ww. jav  a 2  s  .c  o m
    Assert.notNull(to.getBeanName());
    if (entityClass == null) {
        entityClass = to.getEntityClass();
    }
    if (filterClass == null) {
        filterClass = to.getFilterClass();
    }
    Class<?> ec = entityClass;
    Class<?> fc = filterClass;
    if (ec != null) {
        Entity ann = AnnotationUtils.findAnnotation(ec, Entity.class);
        Assert.notNull(ann, "Chain Configuration for '" + getChainNameDisplay() + "' specifies Class '"
                + getEntityClass() + "' which is not a vaild Entity class");
        if (fc == null) {
            if (FilterDefinition.class.isAssignableFrom(ec)) {
                setFilterClass((Class<FilterDefinition>) ec);
            }
        }
        logger.info(getClass().getSimpleName() + " " + getChainNameDisplay() + " for entity class '"
                + entityClass + "'");
    }
    if (fc != null) {
        if (filterInitMethod != null) {
            Assert.notNull(ReflectionUtils.findMethod(getFilterClass(), filterInitMethod),
                    "Chain configuration for '" + getChainNameDisplay()
                            + "' specifies an invalid filter initialization ('" + filterInitMethod
                            + "') for filter class '" + filterClass + "'");
        }
        logger.info(getClass().getSimpleName() + " " + getChainNameDisplay() + " for filter class '"
                + filterClass + "'");
    }
    if (commandFactory == null) {
        Assert.notNull(pageHolderFactory, getClass().getSimpleName() + " " + getChainNameDisplay()
                + " has neither commandFactory nor a pageHolderFactory defined. You need to declare one of both");
        commandFactory = createCommandFactory();
        if (commandFactory instanceof AbstractCommandFactory) {
            AbstractCommandFactory acf = (AbstractCommandFactory) commandFactory;
            acf.setPageHolderFactory(pageHolderFactory);
            acf.setApplicationContext(context);
        }
    }
    setDisabledActions(new ActionConfiguration(Arrays.asList(this.disabled)));
}

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

/**
 * When the object to be copied provides a clone implementation
 * return a clone of the object.//from w  w  w  .j a  va2  s  .c  o m
 * 
 * @param model
 * @return
 */
private static Object cloneCopy(Object model) {
    Object newModel = null;
    Method mth = ReflectionUtils.findMethod(model.getClass(), "clone");
    if (mth != null) {
        try {
            newModel = ReflectionUtils.invokeMethod(mth, model);
        } catch (Exception ex) {
            // ignore any exception during cloning
            if (logger.isDebugEnabled()) {
                logger.debug("Cloning " + model + " failure", ex);
            }
        }
    }
    return newModel;
}

From source file:org.springbyexample.mvc.method.annotation.ServiceHandlerMapping.java

/**
 * Process and setup any converter handlers if one is configured on <code>RestRequestResource</code>.
 *///from ww  w .  jav  a2s .  c om
private void processConverters(RestRequestResource restRequestResource, RequestMappingInfo mapping,
        Method serviceMethod) {
    ApplicationContext ctx = getApplicationContext();
    Class<?> converterClass = (restRequestResource != null ? restRequestResource.converter() : null);

    if (converterClass != null && converterClass != ServiceValueConstants.DEFAULT_CONVERTER_CLASS) {
        @SuppressWarnings("rawtypes")
        ListConverter converter = (ListConverter) ctx.getBean(converterClass);

        String[] pathPatterns = mapping.getPatternsCondition().getPatterns()
                .toArray(ArrayUtils.EMPTY_STRING_ARRAY);

        String methodSuffix = StringUtils.capitalize(converterHandlerInfo.getPropertyName());
        String getterMethodName = "get" + methodSuffix;
        final String setterMethodName = "set" + methodSuffix;

        final Class<?> returnTypeClass = serviceMethod.getReturnType();
        Method getResultsMethod = ReflectionUtils.findMethod(returnTypeClass, getterMethodName);
        final Class<?> resultReturnTypeClass = getResultsMethod.getReturnType();
        Method setResultsMethod = ReflectionUtils.findMethod(returnTypeClass, setterMethodName,
                resultReturnTypeClass);
        final AtomicReference<Method> altSetResultsMethod = new AtomicReference<Method>();

        // issue with ReflectionUtils, setterResultsMethod sometimes null from the command line (not getter?)
        if (setResultsMethod == null) {
            ReflectionUtils.doWithMethods(returnTypeClass, new MethodCallback() {
                @Override
                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                    if (setterMethodName.equals(method.getName())) {
                        altSetResultsMethod.set(method);
                        logger.debug(
                                "Unable to use ReflectionUtils to find setter. returnTypeClass={}  method={} resultReturnTypeClass={}",
                                new Object[] { returnTypeClass, method, resultReturnTypeClass });
                    }
                }
            });
        }

        HandlerInterceptor interceptor = new ConverterHandlerInterceptor(converter, returnTypeClass,
                getResultsMethod, (setResultsMethod != null ? setResultsMethod : altSetResultsMethod.get()));

        MappedInterceptor mappedInterceptor = new MappedInterceptor(pathPatterns, interceptor);
        setInterceptors(new Object[] { mappedInterceptor });

        logger.info("Registered converter post handler for {} with {}.", pathPatterns,
                converterClass.getCanonicalName());
    }
}

From source file:org.springframework.batch.core.jsr.configuration.support.SpringAutowiredAnnotationBeanPostProcessor.java

/**
 * Determine if the annotated field or method requires its dependency.
 * <p>A 'required' dependency means that autowiring should fail when no beans
 * are found. Otherwise, the autowiring process will simply bypass the field
 * or method when no beans are found./*w  ww .j  a  v a2 s  . c  om*/
 * @param annotation the Autowired annotation
 * @return whether the annotation indicates that a dependency is required
 */
protected boolean determineRequiredStatus(Annotation annotation) {
    try {
        Method method = ReflectionUtils.findMethod(annotation.annotationType(), this.requiredParameterName);
        if (method == null) {
            // annotations like @Inject and @Value don't have a method (attribute) named "required"
            // -> default to required status
            return true;
        }
        return (this.requiredParameterValue == (Boolean) ReflectionUtils.invokeMethod(method, annotation));
    } catch (Exception ex) {
        // an exception was thrown during reflective invocation of the required attribute
        // -> default to required status
        return true;
    }
}

From source file:org.springframework.boot.actuate.metrics.export.MetricCopyExporter.java

private void flush(MetricWriter writer) {
    if (writer instanceof CompositeMetricWriter) {
        for (MetricWriter child : (CompositeMetricWriter) writer) {
            flush(child);//from   w  w w  .j a  va2 s .  co m
        }
    }
    try {
        if (ClassUtils.isPresent("java.io.Flushable", null)) {
            if (writer instanceof Flushable) {
                ((Flushable) writer).flush();
                return;
            }
        }
        Method method = ReflectionUtils.findMethod(writer.getClass(), "flush");
        if (method != null) {
            ReflectionUtils.invokeMethod(method, writer);
        }
    } catch (Exception ex) {
        logger.warn("Could not flush MetricWriter: " + ex.getClass() + ": " + ex.getMessage());
    }
}