Example usage for org.springframework.aop.support AopUtils getTargetClass

List of usage examples for org.springframework.aop.support AopUtils getTargetClass

Introduction

In this page you can find the example usage for org.springframework.aop.support AopUtils getTargetClass.

Prototype

public static Class<?> getTargetClass(Object candidate) 

Source Link

Document

Determine the target class of the given bean instance which might be an AOP proxy.

Usage

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Invoke./*from ww w .  j a va2s  . co  m*/
 * 
 * @param <O>
 *          the generic type
 * @param <I>
 *          the generic type
 * @param object
 *          the object
 * @param method
 *          the method
 * @param ignoreAccess
 *          the ignore access
 * @param args
 *          the args
 * @return the object
 */
@SuppressWarnings("unchecked")
public static <O, I> O invokeWithAccessWithArguments(I object, Method method, boolean ignoreAccess,
        Object... args) {
    if (object == null) {
        throw new RuntimeException("Object cannot be null when invoking its methods");
    }

    Object returnObject = null;
    Class<?> clazz = object.getClass();

    try {

        /* call the method */
        if (method != null) {
            if (AopUtils.isAopProxy(object)) {
                InvocationHandler handler = Proxy.getInvocationHandler(object);
                returnObject = handler.invoke(object, method, args);
            } else {
                boolean isAccessible = method.isAccessible();
                try {
                    if (!isAccessible && ignoreAccess) {
                        method.setAccessible(true);
                    }
                    returnObject = method.invoke(object, args);
                } finally {
                    if (ignoreAccess) {
                        method.setAccessible(isAccessible);
                    }
                }
            }
        } else {
            throw new RuntimeException("Method cannot be null");
        }
    } catch (Throwable e) {
        // get the target class if its a proxy
        clazz = AopUtils.getTargetClass(object);

        /* Logger that is available to subclasses */
        Log logger = LogFactory.getLog(clazz);
        // logger.error("Unable to invoke method " + method.getName() + " within "
        // + clazz.getCanonicalName() + "\n"
        // + getStackTrace(e));

        throw new RuntimeException(e);
    }

    return (O) returnObject;
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java

private String mapObjToOutput(Object obj, int maxDepth, Stack<Object> serStack, boolean useGwtArray,
        boolean translateValue) {
    if (serStack.size() == 0) {
        log.log(Level.FINER, "Serializing START {0}", obj);
    }//from www .  j av a  2s. c o  m

    // Avoid recursion
    if (serStack.size() == maxDepth && !(obj instanceof Date || obj instanceof Number || obj instanceof Boolean
            || obj instanceof CharSequence || obj instanceof Enum)) {
        String objId = getIdFromObj(obj);
        return objId == null ? Q + Q : objId;
    }
    if (serStack.contains(obj)) {
        return getIdFromObj(obj);
        // return Q+"ref: "+obj.getClass().getName()+"@"+obj.hashCode()+Q;
    }
    serStack.push(obj);

    String startArray = useGwtArray ? "$wnd.Array.create([" : "[";
    String endArray = useGwtArray ? "])" : "]";

    StringBuilder recordData = new StringBuilder();
    if (obj == null) {
        recordData.append("null");
    } else if (obj instanceof Map) {
        recordData.append("{");
        Map objMap = (Map) obj;
        String delim = "";
        for (Object objKey : objMap.keySet()) {
            recordData.append(delim).append(objKey).append(":")
                    .append(mapObjToOutput(objMap.get(objKey), maxDepth, serStack, useGwtArray, false));
            delim = " , ";
        }
        recordData.append("}");
    } else if (obj instanceof Collection) {
        recordData.append(startArray);
        Collection objSet = (Collection) obj;
        String delim = "";
        for (Object objVal : objSet) {
            recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false));
            delim = " , ";
        }
        recordData.append(endArray);
    } else if (obj instanceof List) {
        recordData.append(startArray);
        List objList = (List) obj;
        String delim = "";
        for (Object objVal : objList) {
            recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false));
            delim = " , ";
        }
        recordData.append(endArray);
    } else if (obj instanceof Object[]) {
        recordData.append(startArray);
        Object[] objArr = (Object[]) obj;
        String delim = "";
        for (Object objVal : objArr) {
            recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false));
            delim = " , ";
        }
        recordData.append(endArray);
    } else if (obj instanceof Date) {
        Date objDate = (Date) obj;
        // recordData.append(Q+dateTimeFormat.format(objDate)+Q);
        recordData.append("new Date(" + objDate.getTime() + ")");
    } else if (obj instanceof Boolean) {
        recordData.append(obj);
    } else if (obj instanceof Number) {
        recordData.append(obj);
    } else if (obj instanceof CharSequence) {
        String strObj = obj.toString();
        if (strObj.startsWith(Main.JAVASCRIPT_PREFIX) && useGwtArray) {
            recordData.append(" ").append(strObj.substring(Main.JAVASCRIPT_PREFIX.length()));
        } else if (strObj.startsWith("function") && useGwtArray) {
            recordData.append(" ").append(strObj);
        } else {
            strObj = translateValue ? translate(strObj) : strObj;
            String escapeString = strObj.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"")
                    .replaceAll("\\r", "\\\\r").replaceAll("\\n", "\\\\n");
            recordData.append(Q + escapeString + Q);
        }
    } else if (obj instanceof Enum) {
        String val = ((Enum) obj).name();
        if (useGwtArray) {
            try {
                Method getValMethod = obj.getClass().getMethod("getValue", (Class[]) null);
                val = (String) getValMethod.invoke(obj, (Object[]) null);
            } catch (Exception e) {
                // no method getValue
            }
        }
        recordData.append(Q + val + Q);
    } else {
        String className = obj.getClass().getName();
        ServiceDescription serviceForClass = findServiceByClassName(className);
        log.log(Level.FINER, "Serializing class {0}", className);
        if (serStack.size() > 2 && serviceForClass != null) {
            recordData.append(getIdFromObj(obj));
        } else {
            // Use reflection
            recordData.append("{");
            String delim = "";
            String jsonPostfix = null;
            Method[] methods = obj.getClass().getMethods();
            for (Method m : methods) {
                boolean translateThisValue = false;
                String mName;
                if (m.getName().startsWith(GET_TRANSLATE)) {
                    translateThisValue = true;
                    mName = m.getName().substring(GET_TRANSLATE_LENGTH);
                } else if (m.getName().startsWith("is")) {
                    mName = m.getName().substring(2);
                } else {
                    mName = m.getName().substring(3);
                }

                if (mName.length() > 1 && Character.isLowerCase(mName.charAt(1))) {
                    mName = mName.substring(0, 1).toLowerCase() + mName.substring(1);
                }

                if (m.getName().startsWith("getJsonPostfix") && m.getParameterTypes().length == 0
                        && String.class.equals(m.getReturnType())) {
                    try {
                        jsonPostfix = (String) m.invoke(obj, new Object[] {});
                    } catch (Throwable e) {
                        log.log(Level.FINE, "Mapping error", e);
                    }
                } else if (!m.getDeclaringClass().getName().startsWith("org.hibernate")
                        && m.getDeclaringClass() != Object.class && m.getDeclaringClass() != Class.class
                        && (m.getName().startsWith("get") || m.getName().startsWith("is"))
                        && m.getParameterTypes().length == 0 && m.getReturnType() != null
                        && !isHiddenField(m.getDeclaringClass().getName(), mName)) {
                    log.log(Level.FINEST, "Reflection invoking name={0} declaringClass={1} on {2}[{3}]",
                            new Object[] { m.getName(), m.getDeclaringClass(), obj, obj.getClass() });
                    try {
                        Object result = m.invoke(obj, new Object[] {});
                        if (result != null) {
                            mName = mName.startsWith("xxx") ? mName.substring(3) : mName;
                            String resultClassName = AopUtils.getTargetClass(result).getName();
                            String idVal = getIdFromObj(result);
                            String valStr;
                            if (findServiceByClassName(resultClassName) != null && idVal != null) {
                                recordData.append(delim).append(mName).append(":").append(idVal);
                                String refField = ds2Ref.get(resultClassName);
                                if (refField != null) {
                                    Object realVal = getValFromObj(refField, result);
                                    valStr = realVal == null ? Q + Q : Q + realVal + Q;
                                } else {
                                    valStr = Q + "UNKNOWN" + Q;
                                }
                                mName = mName + "_VAL";
                                delim = ", ";
                            } else {
                                valStr = mapObjToOutput(result, maxDepth, serStack, useGwtArray,
                                        translateThisValue);
                            }
                            recordData.append(delim).append(mName).append(":").append(valStr);
                            delim = ", ";
                        }
                    } catch (Throwable e) {
                        log.log(Level.FINE, "Mapping error", e);
                    }
                }
            }

            if (jsonPostfix != null) {
                recordData.append(delim).append(jsonPostfix).append("}");
            } else {
                recordData.append("}");
            }
        }
    }
    serStack.pop();
    return recordData.toString();
}

From source file:org.activiti.spring.components.aop.ProcessStartAnnotationBeanPostProcessor.java

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean instanceof AopInfrastructureBean) {
        // Ignore AOP infrastructure such as scoped proxies.
        return bean;
    }/*w  ww .j av a 2  s  .c o m*/
    Class<?> targetClass = AopUtils.getTargetClass(bean);
    if (AopUtils.canApply(this.advisor, targetClass)) {
        if (bean instanceof Advised) {
            ((Advised) bean).addAdvisor(0, this.advisor);
            return bean;
        } else {
            ProxyFactory proxyFactory = new ProxyFactory(bean);
            // Copy our properties (proxyTargetClass etc) inherited from ProxyConfig.
            proxyFactory.copyFrom(this);
            proxyFactory.addAdvisor(this.advisor);
            return proxyFactory.getProxy(this.beanClassLoader);
        }
    } else {
        // No async proxy needed.
        return bean;
    }
}

From source file:org.apache.syncope.core.logic.SyncopeLogic.java

@PreAuthorize("isAuthenticated()")
public PlatformInfo platform() {
    synchronized (MONITOR) {
        if (PLATFORM_INFO == null) {
            PLATFORM_INFO = new PlatformInfo();
            PLATFORM_INFO.setVersion(version);
            PLATFORM_INFO.setBuildNumber(buildNumber);

            if (bundleManager.getLocations() != null) {
                bundleManager.getLocations()
                        .forEach(location -> PLATFORM_INFO.getConnIdLocations().add(location.toASCIIString()));
            }/*from  w ww  .j ava  2  s  . co m*/

            PLATFORM_INFO
                    .setPropagationTaskExecutor(AopUtils.getTargetClass(propagationTaskExecutor).getName());
            PLATFORM_INFO.setAnyObjectWorkflowAdapter(AopUtils.getTargetClass(awfAdapter).getName());
            PLATFORM_INFO.setUserWorkflowAdapter(AopUtils.getTargetClass(uwfAdapter).getName());
            PLATFORM_INFO.setGroupWorkflowAdapter(AopUtils.getTargetClass(gwfAdapter).getName());

            PLATFORM_INFO
                    .setAnyObjectProvisioningManager(AopUtils.getTargetClass(aProvisioningManager).getName());
            PLATFORM_INFO.setUserProvisioningManager(AopUtils.getTargetClass(uProvisioningManager).getName());
            PLATFORM_INFO.setGroupProvisioningManager(AopUtils.getTargetClass(gProvisioningManager).getName());
            PLATFORM_INFO.setVirAttrCache(AopUtils.getTargetClass(virAttrCache).getName());
            PLATFORM_INFO.setPasswordGenerator(AopUtils.getTargetClass(passwordGenerator).getName());
            PLATFORM_INFO.setAnySearchDAO(AopUtils.getTargetClass(anySearchDAO).getName());

            Arrays.stream(ImplementationType.values()).forEach(type -> {
                JavaImplInfo javaImplInfo = new JavaImplInfo();
                javaImplInfo.setType(type);
                javaImplInfo.getClasses().addAll(implLookup.getClassNames(type));

                PLATFORM_INFO.getJavaImplInfos().add(javaImplInfo);
            });
        }

        PLATFORM_INFO.setSelfRegAllowed(isSelfRegAllowed());
        PLATFORM_INFO.setPwdResetAllowed(isPwdResetAllowed());
        PLATFORM_INFO.setPwdResetRequiringSecurityQuestions(isPwdResetRequiringSecurityQuestions());

        PLATFORM_INFO.getEntitlements().clear();
        PLATFORM_INFO.getEntitlements().addAll(EntitlementsHolder.getInstance().getValues());

        AuthContextUtils.execWithAuthContext(AuthContextUtils.getDomain(), () -> {
            PLATFORM_INFO.getAnyTypes().clear();
            PLATFORM_INFO.getAnyTypes().addAll(
                    anyTypeDAO.findAll().stream().map(type -> type.getKey()).collect(Collectors.toList()));

            PLATFORM_INFO.getUserClasses().clear();
            PLATFORM_INFO.getUserClasses().addAll(anyTypeDAO.findUser().getClasses().stream()
                    .map(cls -> cls.getKey()).collect(Collectors.toList()));

            PLATFORM_INFO.getAnyTypeClasses().clear();
            PLATFORM_INFO.getAnyTypeClasses().addAll(
                    anyTypeClassDAO.findAll().stream().map(cls -> cls.getKey()).collect(Collectors.toList()));

            PLATFORM_INFO.getResources().clear();
            PLATFORM_INFO.getResources().addAll(resourceDAO.findAll().stream()
                    .map(resource -> resource.getKey()).collect(Collectors.toList()));
            return null;
        });
    }

    return PLATFORM_INFO;
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAGroupDAO.java

private AnySearchDAO jpaAnySearchDAO() {
    synchronized (this) {
        if (jpaAnySearchDAO == null) {
            if (AopUtils.getTargetClass(searchDAO()).equals(JPAAnySearchDAO.class)) {
                jpaAnySearchDAO = searchDAO();
            } else {
                jpaAnySearchDAO = (AnySearchDAO) ApplicationContextProvider.getBeanFactory()
                        .createBean(JPAAnySearchDAO.class, AbstractBeanDefinition.AUTOWIRE_BY_TYPE, true);
            }/* ww w  .jav  a2 s  .c o m*/
        }
    }
    return jpaAnySearchDAO;
}

From source file:org.artifactory.spring.ArtifactoryApplicationContext.java

@Override
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    super.prepareBeanFactory(beanFactory);
    //Add our own post processor that registers all reloadable beans auto-magically after construction
    beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
        @Override/*from  w  ww.j av  a  2  s .co  m*/
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            Class<?> targetClass = AopUtils.getTargetClass(bean);
            if (ReloadableBean.class.isAssignableFrom(targetClass)) {
                Reloadable annotation;
                if (targetClass.isAnnotationPresent(Reloadable.class)) {
                    annotation = targetClass.getAnnotation(Reloadable.class);
                    Class<? extends ReloadableBean> beanClass = annotation.beanClass();
                    addReloadableBean(beanClass);
                } else {
                    throw new IllegalStateException("Bean " + targetClass.getName()
                            + " requires initialization beans to be initialized, but no such beans were found");
                }
            }
            return bean;
        }

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            //Do nothing
            return bean;
        }
    });
}

From source file:org.artifactory.spring.ArtifactoryApplicationContext.java

private void orderReloadableBeans(Set<Class<? extends ReloadableBean>> beansLeftToInit,
        Class<? extends ReloadableBean> beanClass) {
    if (!beansLeftToInit.contains(beanClass)) {
        // Already done
        return;/*from w  w w. jav  a 2  s .  c o m*/
    }
    ReloadableBean initializingBean = beanForType(beanClass);
    Class<?> targetClass = AopUtils.getTargetClass(initializingBean);
    Reloadable annotation;
    if (targetClass.isAnnotationPresent(Reloadable.class)) {
        annotation = targetClass.getAnnotation(Reloadable.class);
    } else {
        throw new IllegalStateException(
                "Bean " + targetClass.getName() + " requires the @Reloadable annotation to be present.");
    }
    Class<? extends ReloadableBean>[] dependsUpon = annotation.initAfter();
    for (Class<? extends ReloadableBean> doBefore : dependsUpon) {
        //Sanity check that prerequisite bean was registered
        if (!toInitialize.contains(doBefore)) {
            throw new IllegalStateException("Bean '" + beanClass.getName() + "' requires bean '"
                    + doBefore.getName() + "' to be initialized, but no such bean is registered for init.");
        }
        if (!doBefore.isInterface()) {
            throw new IllegalStateException("Cannot order bean with implementation class.\n"
                    + " Please provide an interface extending " + ReloadableBean.class.getName());
        }
        orderReloadableBeans(beansLeftToInit, doBefore);
    }
    // Avoid double init
    if (beansLeftToInit.remove(beanClass)) {
        reloadableBeans.add(initializingBean);
    }
}

From source file:org.kuali.kfs.sys.context.SpringContext.java

public static <T> T getBean(Class<T> type, String name) {
    T bean = null;/*w w w . j  a v a  2s .com*/
    if (SINGLETON_BEANS_BY_NAME_CACHE.containsKey(name)) {
        bean = (T) SINGLETON_BEANS_BY_NAME_CACHE.get(name);
    } else {
        try {
            bean = (T) applicationContext.getBean(name);
            if (applicationContext.isSingleton(name)) {
                synchronized (SINGLETON_BEANS_BY_NAME_CACHE) {
                    SINGLETON_BEANS_BY_NAME_CACHE.put(name, bean);
                }
            }
        } catch (NoSuchBeanDefinitionException nsbde) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Bean with name and type not found in local context: " + name + "/" + type.getName()
                        + " - calling GRL");
            }
            Object remoteServiceBean = getService(name);
            if (remoteServiceBean != null) {
                if (type.isAssignableFrom(AopUtils.getTargetClass(remoteServiceBean))) {
                    bean = (T) remoteServiceBean;
                    // assume remote beans are services and thus singletons
                    synchronized (SINGLETON_BEANS_BY_NAME_CACHE) {
                        SINGLETON_BEANS_BY_NAME_CACHE.put(name, bean);
                    }
                }
            }
            if (bean == null) {
                throw new RuntimeException(
                        "No bean of this type and name exist in the application context or from the GRL: "
                                + type.getName() + ", " + name);
            }
        }
    }
    return bean;
}

From source file:org.openspaces.events.AbstractEventListenerContainer.java

private void initializeExceptionHandler() {
    if (exceptionHandler == null && getActualEventListener() != null) {
        final AtomicReference<Method> ref = new AtomicReference<Method>();
        ReflectionUtils.doWithMethods(AopUtils.getTargetClass(getActualEventListener()),
                new ReflectionUtils.MethodCallback() {
                    public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                        if (method.isAnnotationPresent(ExceptionHandler.class)) {
                            ref.set(method);
                        }//from  w w w.  j a  va 2  s  .  c om
                    }
                });
        if (ref.get() != null) {
            ref.get().setAccessible(true);
            try {
                setExceptionHandler((EventExceptionHandler) ref.get().invoke(getActualEventListener()));
            } catch (Exception e) {
                throw new IllegalArgumentException(
                        "Failed to set EventExceptionHandler from method [" + ref.get().getName() + "]", e);
            }
        }
    }
}

From source file:org.openspaces.remoting.RemotingAnnotationBeanPostProcessor.java

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if (bean == null) {
        return bean;
    }//from  www.ja v a 2s .c o  m
    Class beanClass = AopUtils.getTargetClass(bean);
    if (beanClass == null) {
        return bean;
    }
    RemotingService remotingService = AnnotationUtils.findAnnotation(beanClass, RemotingService.class);
    if (remotingService != null) {
        SpaceRemotingServiceExporter exporter;
        if (StringUtils.hasLength(remotingService.exporter())) {
            exporter = (SpaceRemotingServiceExporter) applicationContext.getBean(remotingService.exporter());
            if (exporter == null) {
                throw new IllegalArgumentException("Failed to find exporter under name ["
                        + remotingService.exporter() + "] for bean [" + beanName + "]");
            }
        } else {
            Map exporters = applicationContext.getBeansOfType(SpaceRemotingServiceExporter.class);
            if (exporters.isEmpty()) {
                throw new IllegalArgumentException(
                        "No service exporters are defined within the context, can't register remote service bean ["
                                + beanName + "]");
            }
            if (exporters.size() > 1) {
                throw new IllegalStateException(
                        "More than one service exporter are defined within the context, please specify the exact service exported to register with");
            }
            exporter = (SpaceRemotingServiceExporter) exporters.values().iterator().next();
        }
        exporter.addService(beanName, bean);
    }
    return bean;
}