Example usage for org.springframework.util ReflectionUtils handleReflectionException

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

Introduction

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

Prototype

public static void handleReflectionException(Exception ex) 

Source Link

Document

Handle the given reflection exception.

Usage

From source file:org.beangle.security.web.context.HttpSessionContextIntegrationFilter.java

/**
 * Gets the security context from the session (if available) and returns it.
 * <p/>/*from ww  w.  ja  v  a  2 s.  co  m*/
 * If the session is null, the context object is null or the context object stored in the
 * session is not an instance of SecurityContext it will return null.
 * <p/>
 * If <tt>cloneFromHttpSession</tt> is set to true, it will attempt to clone the context object
 * and return the cloned instance.
 * 
 * @param httpSession
 *            the session obtained from the request.
 */
private SecurityContext readSecurityContextFromSession(HttpSession httpSession) {
    if (httpSession == null) {
        logger.debug("No HttpSession currently exists");
        return null;
    }

    // Session exists, so try to obtain a context from it.
    Object contextFromSessionObject = httpSession.getAttribute(SECURITY_CONTEXT_KEY);
    if (contextFromSessionObject == null) {
        logger.debug("HttpSession returned null object for BEANGLE_SECURITY_CONTEXT");
        return null;
    }

    // We now have the security context object from the session.

    // Clone if required (see SEC-356)
    if (cloneFromHttpSession) {
        Validate.isTrue(contextFromSessionObject instanceof Cloneable,
                "Context must implement Clonable and provide a Object.clone() method");
        try {
            Method m = contextFromSessionObject.getClass().getMethod("clone", new Class[] {});
            if (!m.isAccessible()) {
                m.setAccessible(true);
            }
            contextFromSessionObject = m.invoke(contextFromSessionObject, new Object[] {});
        } catch (Exception ex) {
            ReflectionUtils.handleReflectionException(ex);
        }
    }

    if (!(contextFromSessionObject instanceof SecurityContext)) {
        if (logger.isWarnEnabled()) {
            logger.warn("BEANGLE_SECURITY_CONTEXT did not contain a SecurityContext but contained: '"
                    + contextFromSessionObject + "'; are you improperly modifying the HttpSession directly "
                    + "(you should always use SecurityContextHolder) or using the HttpSession attribute "
                    + "reserved for this class?");
        }

        return null;
    }

    // Everything OK. The only non-null return from this method.

    return (SecurityContext) contextFromSessionObject;
}

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

protected Constructor<?> lookupConstructor(String className, Class<?>... argTypes) {
    try {//from  w  w w.j  a  va2  s.co  m
        Class<?> clazz = ReflectHelper.classForName(className);
        Constructor<?> constructor = clazz.getConstructor(argTypes);
        constructor.setAccessible(true);
        return constructor;
    } catch (ClassNotFoundException e) {
        ReflectionUtils.handleReflectionException(e);
    } catch (NoSuchMethodException e) {
        ReflectionUtils.handleReflectionException(e);
    } catch (SecurityException e) {
        ReflectionUtils.handleReflectionException(e);
    }
    return null;
}

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

protected Object create(Constructor<?> constructor, Object... args) {
    try {// ww  w  .j  ava  2  s. c o  m
        return constructor.newInstance(args);
    } catch (InstantiationException e) {
        ReflectionUtils.handleReflectionException(e);
    } catch (IllegalAccessException e) {
        ReflectionUtils.handleReflectionException(e);
    } catch (IllegalArgumentException e) {
        ReflectionUtils.handleReflectionException(e);
    } catch (InvocationTargetException e) {
        ReflectionUtils.handleInvocationTargetException(e);
    }
    return null;
}

From source file:org.openengsb.core.util.BeanUtilsExtended.java

/**
 * Creates a new instance of the beanType and populates it with the property-values from the map
 *
 * @throws IllegalArgumentException if the bean cannot be populated because of errors in the definition of the
 *         beantype/*from ww w. j  a v a2 s  .c  om*/
 */
public static <BeanType> BeanType createBeanFromAttributeMap(Class<BeanType> beanType,
        Map<String, ? extends Object> attributeValues) {
    BeanType instance;
    try {
        instance = beanType.newInstance();
        BeanUtils.populate(instance, attributeValues);
    } catch (Exception e) {
        ReflectionUtils.handleReflectionException(e);
        throw new IllegalStateException("Should never get here");
    }
    return instance;
}

From source file:org.openengsb.core.util.BeanUtilsExtended.java

/**
 * returns the result of {@link BeanUtils#describe(Object)} converted to the proper generic map-type.
 *
 * Exceptions from Reflection are wrapped in {@link IllegalArgumentException}s
 *
 * @throws IllegalArgumentException if some property in the bean cannot be accessed
 *///from  w  ww. j  a  va2s .  co m
@SuppressWarnings("unchecked")
public static Map<String, String> buildStringAttributeMap(Object bean) throws IllegalArgumentException {
    try {
        return BeanUtils.describe(bean);
    } catch (Exception e) {
        ReflectionUtils.handleReflectionException(e);
        throw new IllegalStateException("Should never get here");
    }
}

From source file:org.pssframework.dao.BaseHibernateDao.java

/**
 * ???./*from ww  w . ja  va2s  . c o m*/
 *
 * @param uniquePropertyNames POJO???,? "name,loginid,password"
 */
public boolean isUnique(E entity, String uniquePropertyNames) {
    Assert.hasText(uniquePropertyNames);
    Criteria criteria = getSession().createCriteria(getEntityClass()).setProjection(Projections.rowCount());
    String[] nameList = uniquePropertyNames.split(",");
    try {
        // 
        for (int i = 0; i < nameList.length; i++) {
            criteria.add(Restrictions.eq(nameList[i], PropertyUtils.getProperty(entity, nameList[i])));
        }

        // ?update,entity.

        String idName = getSessionFactory().getClassMetadata(entity.getClass()).getIdentifierPropertyName();
        if (idName != null) {
            // ?entity
            Serializable id = (Serializable) PropertyUtils.getProperty(entity, idName);

            // id!=null,,?update,
            if (id != null)
                criteria.add(Restrictions.not(Restrictions.eq(idName, id)));
        }
    } catch (Exception e) {
        ReflectionUtils.handleReflectionException(e);
    }
    return ((Number) criteria.uniqueResult()).intValue() == 0;
}

From source file:org.springframework.amqp.rabbit.annotation.RabbitListenerAnnotationBeanPostProcessor.java

private Method checkProxy(Method method, Object bean) {
    if (AopUtils.isJdkDynamicProxy(bean)) {
        try {//from  ww  w . j  av  a 2 s  .c o m
            // Found a @RabbitListener method on the target class for this JDK proxy ->
            // is it also present on the proxy itself?
            method = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
            Class<?>[] proxiedInterfaces = ((Advised) bean).getProxiedInterfaces();
            for (Class<?> iface : proxiedInterfaces) {
                try {
                    method = iface.getMethod(method.getName(), method.getParameterTypes());
                    break;
                } catch (NoSuchMethodException noMethod) {
                }
            }
        } catch (SecurityException ex) {
            ReflectionUtils.handleReflectionException(ex);
        } catch (NoSuchMethodException ex) {
            throw new IllegalStateException(String.format(
                    "@RabbitListener method '%s' found on bean target class '%s', "
                            + "but not found in any interface(s) for bean JDK proxy. Either "
                            + "pull the method up to an interface or switch to subclass (CGLIB) "
                            + "proxies by setting proxy-target-class/proxyTargetClass " + "attribute to 'true'",
                    method.getName(), method.getDeclaringClass().getSimpleName()));
        }
    }
    return method;
}

From source file:org.springframework.core.ReflectiveVisitorHelper.java

/**
 * Use reflection to call the appropriate <code>visit</code> method
 * on the provided visitor, passing in the specified argument.
 * @param visitor the visitor encapsulating the logic to process the argument
 * @param argument the argument to dispatch
 * @throws IllegalArgumentException if the visitor parameter is null
 *//*from   w w  w . j  a va2s. c  o  m*/
public Object invokeVisit(Object visitor, Object argument) {
    Assert.notNull(visitor, "The visitor to visit is required");
    // Perform call back on the visitor through reflection.
    Method method = getMethod(visitor.getClass(), argument);
    if (method == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("No method found by reflection for visitor class [" + visitor.getClass().getName()
                    + "] and argument of type [" + (argument != null ? argument.getClass().getName() : "")
                    + "]");
        }
        return null;
    }
    try {
        Object[] args = null;
        if (argument != null) {
            args = new Object[] { argument };
        }
        if (!Modifier.isPublic(method.getModifiers()) && !method.isAccessible()) {
            method.setAccessible(true);
        }
        return method.invoke(visitor, args);

    } catch (Exception ex) {
        ReflectionUtils.handleReflectionException(ex);
        throw new IllegalStateException("Should never get here");
    }
}

From source file:org.springframework.kafka.annotation.KafkaListenerAnnotationBeanPostProcessor.java

private Method checkProxy(Method methodArg, Object bean) {
    Method method = methodArg;/*from ww  w  .ja  v  a 2  s.  c o m*/
    if (AopUtils.isJdkDynamicProxy(bean)) {
        try {
            // Found a @KafkaListener method on the target class for this JDK proxy ->
            // is it also present on the proxy itself?
            method = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
            Class<?>[] proxiedInterfaces = ((Advised) bean).getProxiedInterfaces();
            for (Class<?> iface : proxiedInterfaces) {
                try {
                    method = iface.getMethod(method.getName(), method.getParameterTypes());
                    break;
                } catch (NoSuchMethodException noMethod) {
                }
            }
        } catch (SecurityException ex) {
            ReflectionUtils.handleReflectionException(ex);
        } catch (NoSuchMethodException ex) {
            throw new IllegalStateException(String.format(
                    "@KafkaListener method '%s' found on bean target class '%s', "
                            + "but not found in any interface(s) for bean JDK proxy. Either "
                            + "pull the method up to an interface or switch to subclass (CGLIB) "
                            + "proxies by setting proxy-target-class/proxyTargetClass " + "attribute to 'true'",
                    method.getName(), method.getDeclaringClass().getSimpleName()), ex);
        }
    }
    return method;
}

From source file:org.springframework.orm.toplink.LocalSessionFactory.java

/**
 * Load the specified DatabaseSession from the TopLink <code>sessions.xml</code>
 * configuration file./*ww w  .  j  av  a2 s.co m*/
 * @param configLocation the class path location of the <code>sessions.xml</code> file
 * @param sessionName the name of the TopLink Session in the configuration file
 * @param sessionClassLoader the class loader to use
 * @return the DatabaseSession instance
 * @throws TopLinkException in case of errors
 */
protected DatabaseSession loadDatabaseSession(String configLocation, String sessionName,
        ClassLoader sessionClassLoader) throws TopLinkException {

    SessionManager manager = getSessionManager();

    // Try to find TopLink 10.1.3 XMLSessionConfigLoader.
    Class loaderClass = null;
    Method getSessionMethod = null;
    try {
        loaderClass = Class.forName("oracle.toplink.tools.sessionconfiguration.XMLSessionConfigLoader");
        getSessionMethod = SessionManager.class.getMethod("getSession", new Class[] { loaderClass, String.class,
                ClassLoader.class, boolean.class, boolean.class, boolean.class });
        if (logger.isDebugEnabled()) {
            logger.debug("Using TopLink 10.1.3 XMLSessionConfigLoader");
        }
    } catch (Exception ex) {
        // TopLink 10.1.3 XMLSessionConfigLoader not found ->
        // fall back to TopLink 9.0.4 XMLLoader.
        if (logger.isDebugEnabled()) {
            logger.debug("Using TopLink 9.0.4 XMLLoader");
        }
        XMLLoader loader = new XMLLoader(configLocation);
        return (DatabaseSession) manager.getSession(loader, sessionName, sessionClassLoader, false, false);
    }

    // TopLink 10.1.3 XMLSessionConfigLoader found -> create loader instance
    // through reflection and fetch specified Session from SessionManager.
    // This invocation will check if the ClassLoader passed in is the same
    // as the one used to a session currently loaded with the same "sessionName"
    // If the ClassLoaders are different, then this LocalSessionFactory is being
    // re-loaded after a hot-deploy and the existing DatabaseSession will be logged
    // out and re-built from scratch.
    try {
        Constructor ctor = loaderClass.getConstructor(new Class[] { String.class });
        Object loader = ctor.newInstance(new Object[] { configLocation });
        return (DatabaseSession) getSessionMethod.invoke(manager, new Object[] { loader, sessionName,
                sessionClassLoader, Boolean.FALSE, Boolean.FALSE, Boolean.TRUE });
    } catch (Exception ex) {
        ReflectionUtils.handleReflectionException(ex);
        throw new IllegalStateException("Should never get here");
    }
}