Search in sources :

Example 1 with ParameterNameDiscoverer

use of org.springframework.core.ParameterNameDiscoverer in project head by mifos.

the class AspectJRESTApprovalInterceptor method profile.

@Around("restMethods() && requestMapping() && excludeAPI() && exludeRestfulServices()")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
    Signature signature = pjp.getStaticPart().getSignature();
    LOG.debug(this.getClass().getSimpleName() + " staring");
    // FIXME : somehow autowiring is not working
    if (approvalService == null) {
        approvalService = ApplicationContextProvider.getBean(ApprovalService.class);
    }
    if (configurationServiceFacade == null) {
        configurationServiceFacade = ApplicationContextProvider.getBean(ConfigurationServiceFacade.class);
    }
    if (parameterNameDiscoverer == null) {
        parameterNameDiscoverer = ApplicationContextProvider.getBean(ParameterNameDiscoverer.class);
    }
    if (!RESTConfigKey.isApprovalRequired(configurationServiceFacade)) {
        LOG.debug(pjp.getSignature() + " skip approval");
        return pjp.proceed();
    }
    if (signature instanceof MethodSignature) {
        MethodSignature ms = (MethodSignature) signature;
        Method m = ms.getMethod();
        RequestMapping mapping = m.getAnnotation(RequestMapping.class);
        if (isReadOnly(mapping)) {
            LOG.debug(m.getName() + " is read only, hence returning control");
            return pjp.proceed();
        }
        Class<?> methodClassType = m.getDeclaringClass();
        if (!methodClassType.getSimpleName().endsWith("RESTController")) {
            LOG.debug(m.getName() + " is not from REST controller, hence returning control");
            return pjp.proceed();
        }
        Object[] argValues = pjp.getArgs();
        Class<?>[] argTypes = m.getParameterTypes();
        String methodName = m.getName();
        String[] names = parameterNameDiscoverer.getParameterNames(m);
        MethodArgHolder args = new MethodArgHolder(argTypes, argValues, names);
        ApprovalMethod method = new ApprovalMethod(methodName, methodClassType, args);
        approvalService.create(method);
    }
    return pjp.proceed();
}
Also used : MethodSignature(org.aspectj.lang.reflect.MethodSignature) ParameterNameDiscoverer(org.springframework.core.ParameterNameDiscoverer) ApprovalService(org.mifos.rest.approval.service.ApprovalService) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) ApprovalMethod(org.mifos.rest.approval.domain.ApprovalMethod) Method(java.lang.reflect.Method) ConfigurationServiceFacade(org.mifos.config.servicefacade.ConfigurationServiceFacade) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) MethodArgHolder(org.mifos.rest.approval.domain.MethodArgHolder) Signature(org.aspectj.lang.Signature) MethodSignature(org.aspectj.lang.reflect.MethodSignature) ApprovalMethod(org.mifos.rest.approval.domain.ApprovalMethod) Around(org.aspectj.lang.annotation.Around)

Example 2 with ParameterNameDiscoverer

use of org.springframework.core.ParameterNameDiscoverer in project spring-framework by spring-projects.

the class ConstructorResolver method autowireConstructor.

/**
	 * "autowire constructor" (with constructor arguments by type) behavior.
	 * Also applied if explicit constructor argument values are specified,
	 * matching all remaining arguments with beans from the bean factory.
	 * <p>This corresponds to constructor injection: In this mode, a Spring
	 * bean factory is able to host components that expect constructor-based
	 * dependency resolution.
	 * @param beanName the name of the bean
	 * @param mbd the merged bean definition for the bean
	 * @param chosenCtors chosen candidate constructors (or {@code null} if none)
	 * @param explicitArgs argument values passed in programmatically via the getBean method,
	 * or {@code null} if none (-> use constructor argument values from bean definition)
	 * @return a BeanWrapper for the new instance
	 */
public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd, Constructor<?>[] chosenCtors, final Object[] explicitArgs) {
    BeanWrapperImpl bw = new BeanWrapperImpl();
    this.beanFactory.initBeanWrapper(bw);
    Constructor<?> constructorToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;
    if (explicitArgs != null) {
        argsToUse = explicitArgs;
    } else {
        Object[] argsToResolve = null;
        synchronized (mbd.constructorArgumentLock) {
            constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                // Found a cached constructor...
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) {
            argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
        }
    }
    if (constructorToUse == null) {
        // Need to resolve the constructor.
        boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
        ConstructorArgumentValues resolvedValues = null;
        int minNrOfArgs;
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        } else {
            ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
            resolvedValues = new ConstructorArgumentValues();
            minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
        }
        // Take specified constructors, if any.
        Constructor<?>[] candidates = chosenCtors;
        if (candidates == null) {
            Class<?> beanClass = mbd.getBeanClass();
            try {
                candidates = (mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors() : beanClass.getConstructors());
            } catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Resolution of declared constructors on bean Class [" + beanClass.getName() + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
            }
        }
        AutowireUtils.sortConstructors(candidates);
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Set<Constructor<?>> ambiguousConstructors = null;
        LinkedList<UnsatisfiedDependencyException> causes = null;
        for (Constructor<?> candidate : candidates) {
            Class<?>[] paramTypes = candidate.getParameterTypes();
            if (constructorToUse != null && argsToUse.length > paramTypes.length) {
                // do not look any further, there are only less greedy constructors left.
                break;
            }
            if (paramTypes.length < minNrOfArgs) {
                continue;
            }
            ArgumentsHolder argsHolder;
            if (resolvedValues != null) {
                try {
                    String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
                    if (paramNames == null) {
                        ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                        if (pnd != null) {
                            paramNames = pnd.getParameterNames(candidate);
                        }
                    }
                    argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames, getUserDeclaredConstructor(candidate), autowiring);
                } catch (UnsatisfiedDependencyException ex) {
                    if (this.beanFactory.logger.isTraceEnabled()) {
                        this.beanFactory.logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
                    }
                    // Swallow and try next constructor.
                    if (causes == null) {
                        causes = new LinkedList<>();
                    }
                    causes.add(ex);
                    continue;
                }
            } else {
                // Explicit arguments given -> arguments length must match exactly.
                if (paramTypes.length != explicitArgs.length) {
                    continue;
                }
                argsHolder = new ArgumentsHolder(explicitArgs);
            }
            int typeDiffWeight = (mbd.isLenientConstructorResolution() ? argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
            // Choose this constructor if it represents the closest match.
            if (typeDiffWeight < minTypeDiffWeight) {
                constructorToUse = candidate;
                argsHolderToUse = argsHolder;
                argsToUse = argsHolder.arguments;
                minTypeDiffWeight = typeDiffWeight;
                ambiguousConstructors = null;
            } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
                if (ambiguousConstructors == null) {
                    ambiguousConstructors = new LinkedHashSet<>();
                    ambiguousConstructors.add(constructorToUse);
                }
                ambiguousConstructors.add(candidate);
            }
        }
        if (constructorToUse == null) {
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Could not resolve matching constructor " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
        } else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Ambiguous constructor matches found in bean '" + beanName + "' " + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " + ambiguousConstructors);
        }
        if (explicitArgs == null) {
            argsHolderToUse.storeCache(mbd, constructorToUse);
        }
    }
    try {
        Object beanInstance;
        if (System.getSecurityManager() != null) {
            final Constructor<?> ctorToUse = constructorToUse;
            final Object[] argumentsToUse = argsToUse;
            beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {
                    return beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, beanFactory, ctorToUse, argumentsToUse);
                }
            }, beanFactory.getAccessControlContext());
        } else {
            beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
        }
        bw.setBeanInstance(beanInstance);
        return bw;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Bean instantiation via constructor failed", ex);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) ParameterNameDiscoverer(org.springframework.core.ParameterNameDiscoverer) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) PrivilegedAction(java.security.PrivilegedAction) Constructor(java.lang.reflect.Constructor) InjectionPoint(org.springframework.beans.factory.InjectionPoint) LinkedList(java.util.LinkedList) UnsatisfiedDependencyException(org.springframework.beans.factory.UnsatisfiedDependencyException) BeanCreationException(org.springframework.beans.factory.BeanCreationException) BeansException(org.springframework.beans.BeansException) BeanDefinitionStoreException(org.springframework.beans.factory.BeanDefinitionStoreException) TypeMismatchException(org.springframework.beans.TypeMismatchException) ConstructorArgumentValues(org.springframework.beans.factory.config.ConstructorArgumentValues)

Example 3 with ParameterNameDiscoverer

use of org.springframework.core.ParameterNameDiscoverer in project spring-framework by spring-projects.

the class LocalValidatorFactoryBean method configureParameterNameProviderIfPossible.

private void configureParameterNameProviderIfPossible(Configuration<?> configuration) {
    // TODO: inner class
    final ParameterNameDiscoverer discoverer = this.parameterNameDiscoverer;
    final ParameterNameProvider defaultProvider = configuration.getDefaultParameterNameProvider();
    configuration.parameterNameProvider(new ParameterNameProvider() {

        @Override
        public List<String> getParameterNames(Constructor<?> constructor) {
            String[] paramNames = discoverer.getParameterNames(constructor);
            return (paramNames != null ? Arrays.asList(paramNames) : defaultProvider.getParameterNames(constructor));
        }

        @Override
        public List<String> getParameterNames(Method method) {
            String[] paramNames = discoverer.getParameterNames(method);
            return (paramNames != null ? Arrays.asList(paramNames) : defaultProvider.getParameterNames(method));
        }
    });
}
Also used : ParameterNameProvider(javax.validation.ParameterNameProvider) ParameterNameDiscoverer(org.springframework.core.ParameterNameDiscoverer) DefaultParameterNameDiscoverer(org.springframework.core.DefaultParameterNameDiscoverer) List(java.util.List) Method(java.lang.reflect.Method)

Example 4 with ParameterNameDiscoverer

use of org.springframework.core.ParameterNameDiscoverer in project spring-framework by spring-projects.

the class AbstractReflectiveMBeanInfoAssembler method getOperationParameters.

/**
	 * Create parameter info for the given method.
	 * <p>The default implementation returns an empty array of {@code MBeanParameterInfo}.
	 * @param method the {@code Method} to get the parameter information for
	 * @param beanKey the key associated with the MBean in the beans map
	 * of the {@code MBeanExporter}
	 * @return the {@code MBeanParameterInfo} array
	 */
protected MBeanParameterInfo[] getOperationParameters(Method method, String beanKey) {
    ParameterNameDiscoverer paramNameDiscoverer = getParameterNameDiscoverer();
    String[] paramNames = (paramNameDiscoverer != null ? paramNameDiscoverer.getParameterNames(method) : null);
    if (paramNames == null) {
        return new MBeanParameterInfo[0];
    }
    MBeanParameterInfo[] info = new MBeanParameterInfo[paramNames.length];
    Class<?>[] typeParameters = method.getParameterTypes();
    for (int i = 0; i < info.length; i++) {
        info[i] = new MBeanParameterInfo(paramNames[i], typeParameters[i].getName(), paramNames[i]);
    }
    return info;
}
Also used : ParameterNameDiscoverer(org.springframework.core.ParameterNameDiscoverer) DefaultParameterNameDiscoverer(org.springframework.core.DefaultParameterNameDiscoverer) MBeanParameterInfo(javax.management.MBeanParameterInfo)

Example 5 with ParameterNameDiscoverer

use of org.springframework.core.ParameterNameDiscoverer in project spring-security by spring-projects.

the class DefaultSecurityParameterNameDiscovererTests method constructorDefault.

@Test
public void constructorDefault() {
    List<ParameterNameDiscoverer> discoverers = (List<ParameterNameDiscoverer>) ReflectionTestUtils.getField(discoverer, "parameterNameDiscoverers");
    assertThat(discoverers.size()).isEqualTo(2);
    ParameterNameDiscoverer annotationDisc = discoverers.get(0);
    assertThat(annotationDisc).isInstanceOf(AnnotationParameterNameDiscoverer.class);
    Set<String> annotationsToUse = (Set<String>) ReflectionTestUtils.getField(annotationDisc, "annotationClassesToUse");
    assertThat(annotationsToUse).containsOnly(P.class.getName());
    assertThat(discoverers.get(1).getClass()).isEqualTo(DefaultParameterNameDiscoverer.class);
}
Also used : P(org.springframework.security.access.method.P) Set(java.util.Set) ParameterNameDiscoverer(org.springframework.core.ParameterNameDiscoverer) DefaultParameterNameDiscoverer(org.springframework.core.DefaultParameterNameDiscoverer) LocalVariableTableParameterNameDiscoverer(org.springframework.core.LocalVariableTableParameterNameDiscoverer) List(java.util.List) Test(org.junit.Test)

Aggregations

ParameterNameDiscoverer (org.springframework.core.ParameterNameDiscoverer)8 DefaultParameterNameDiscoverer (org.springframework.core.DefaultParameterNameDiscoverer)5 Method (java.lang.reflect.Method)4 LinkedHashSet (java.util.LinkedHashSet)3 List (java.util.List)3 BeanDefinitionStoreException (org.springframework.beans.factory.BeanDefinitionStoreException)3 ConstructorArgumentValues (org.springframework.beans.factory.config.ConstructorArgumentValues)3 PrivilegedAction (java.security.PrivilegedAction)2 LinkedList (java.util.LinkedList)2 Set (java.util.Set)2 Test (org.junit.Test)2 BeanWrapperImpl (org.springframework.beans.BeanWrapperImpl)2 BeansException (org.springframework.beans.BeansException)2 TypeMismatchException (org.springframework.beans.TypeMismatchException)2 BeanCreationException (org.springframework.beans.factory.BeanCreationException)2 InjectionPoint (org.springframework.beans.factory.InjectionPoint)2 UnsatisfiedDependencyException (org.springframework.beans.factory.UnsatisfiedDependencyException)2 LocalVariableTableParameterNameDiscoverer (org.springframework.core.LocalVariableTableParameterNameDiscoverer)2 P (org.springframework.security.access.method.P)2 Constructor (java.lang.reflect.Constructor)1