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.springframework.scheduling.quartz.SchedulerFactoryBean.java

/**
 * Add the given calendar to the Scheduler, checking for the
 * corresponding Quartz 1.4 or Quartz 1.3 method
 * (which differ in 1.4's additional "updateTriggers" flag).
 * @param calendarName the name of the calendar
 * @param calendar the Calendar object/*from  w w  w .j  ava  2 s  . c om*/
 * @see org.quartz.Scheduler#addCalendar
 */
private void addCalendarToScheduler(String calendarName, Calendar calendar) throws SchedulerException {
    try {
        try {
            // Try Quartz 1.4 (with "updateTriggers" flag).
            Method addCalendarMethod = this.scheduler.getClass().getMethod("addCalendar",
                    new Class[] { String.class, Calendar.class, boolean.class, boolean.class });
            addCalendarMethod.invoke(this.scheduler,
                    new Object[] { calendarName, calendar, Boolean.TRUE, Boolean.TRUE });
        } catch (NoSuchMethodException ex) {
            // Try Quartz 1.3 (without "updateTriggers" flag).
            Method addCalendarMethod = this.scheduler.getClass().getMethod("addCalendar",
                    new Class[] { String.class, Calendar.class, boolean.class });
            addCalendarMethod.invoke(this.scheduler, new Object[] { calendarName, calendar, Boolean.TRUE });
        }
    } catch (InvocationTargetException ex) {
        if (ex.getTargetException() instanceof SchedulerException) {
            throw (SchedulerException) ex.getTargetException();
        }
        ReflectionUtils.handleInvocationTargetException(ex);
    } catch (Exception ex) {
        ReflectionUtils.handleReflectionException(ex);
    }
}

From source file:org.springframework.security.extensions.portlet.PortletSessionContextIntegrationInterceptor.java

private boolean preHandle(PortletRequest request, PortletResponse response, Object handler) throws Exception {

    PortletSession portletSession = null;
    boolean portletSessionExistedAtStartOfRequest = false;

    // see if the portlet session already exists (or should be eagerly created)
    try {//from  w ww  .j  av  a 2 s  .c o  m
        portletSession = request.getPortletSession(forceEagerSessionCreation);
    } catch (IllegalStateException ignored) {
    }

    // if there is a session, then see if there is a contextClass to bring in
    if (portletSession != null) {

        // remember that the session already existed
        portletSessionExistedAtStartOfRequest = true;

        // attempt to retrieve the contextClass from the session
        Object contextFromSessionObject = portletSession.getAttribute(SPRING_SECURITY_CONTEXT_KEY,
                portletSessionScope());

        // if we got a contextClass then place it into the holder
        if (contextFromSessionObject != null) {

            // if we are supposed to clone it, then do so
            if (cloneFromPortletSession) {
                Assert.isInstanceOf(Cloneable.class, contextFromSessionObject,
                        "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 what we got is a valid contextClass then place it into the holder, otherwise create a new one
            if (contextFromSessionObject instanceof SecurityContext) {
                if (logger.isDebugEnabled())
                    logger.debug("Obtained from SPRING_SECURITY_CONTEXT a valid SecurityContext and "
                            + "set to SecurityContextHolder: '" + contextFromSessionObject + "'");
                SecurityContextHolder.setContext((SecurityContext) contextFromSessionObject);
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("SPRING_SECURITY_CONTEXT did not contain a SecurityContext but contained: '"
                            + contextFromSessionObject
                            + "'; are you improperly modifying the PortletSession directly "
                            + "(you should always use SecurityContextHolder) or using the PortletSession attribute "
                            + "reserved for this class? - new SecurityContext instance associated with "
                            + "SecurityContextHolder");
                SecurityContextHolder.setContext(generateNewContext());
            }

        } else {

            // there was no contextClass in the session, so create a new contextClass and put it in the holder
            if (logger.isDebugEnabled())
                logger.debug("PortletSession returned null object for SPRING_SECURITY_CONTEXT - new "
                        + "SecurityContext instance associated with SecurityContextHolder");
            SecurityContextHolder.setContext(generateNewContext());
        }

    } else {

        // there was no session, so create a new contextClass and place it in the holder
        if (logger.isDebugEnabled())
            logger.debug("No PortletSession currently exists - new SecurityContext instance "
                    + "associated with SecurityContextHolder");
        SecurityContextHolder.setContext(generateNewContext());

    }

    // place attributes onto the request to remember if the session existed and the hashcode of the contextClass
    request.setAttribute(SESSION_EXISTED, new Boolean(portletSessionExistedAtStartOfRequest));
    request.setAttribute(CONTEXT_HASHCODE, new Integer(SecurityContextHolder.getContext().hashCode()));

    return true;
}

From source file:org.springframework.test.util.ReflectionTestUtils.java

/**
 * Invoke the method with the given {@code name} on the supplied target
 * object with the supplied arguments./* ww w .  j ava  2  s .  c  om*/
 * <p>This method traverses the class hierarchy in search of the desired
 * method. In addition, an attempt will be made to make non-{@code public}
 * methods <em>accessible</em>, thus allowing one to invoke {@code protected},
 * {@code private}, and <em>package-private</em> methods.
 * @param target the target object on which to invoke the specified method
 * @param name the name of the method to invoke
 * @param args the arguments to provide to the method
 * @return the invocation result, if any
 * @see MethodInvoker
 * @see ReflectionUtils#makeAccessible(Method)
 * @see ReflectionUtils#invokeMethod(Method, Object, Object[])
 * @see ReflectionUtils#handleReflectionException(Exception)
 */
@SuppressWarnings("unchecked")
@Nullable
public static <T> T invokeMethod(Object target, String name, Object... args) {
    Assert.notNull(target, "Target object must not be null");
    Assert.hasText(name, "Method name must not be empty");

    try {
        MethodInvoker methodInvoker = new MethodInvoker();
        methodInvoker.setTargetObject(target);
        methodInvoker.setTargetMethod(name);
        methodInvoker.setArguments(args);
        methodInvoker.prepare();

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Invoking method '%s' on %s with arguments %s", name,
                    safeToString(target), ObjectUtils.nullSafeToString(args)));
        }

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

From source file:org.springmodules.validation.valang.javascript.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
 *///w ww  .ja  v a  2s .  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.setAccessible(true);
        }
        return method.invoke(visitor, args);
    } catch (Exception ex) {
        ReflectionUtils.handleReflectionException(ex);
        throw new IllegalStateException("Should never get here");
    }
}

From source file:org.squashtest.tm.domain.event.RequirementModificationEventPublisherAspect.java

private Object readOldValue(RequirementVersion req, String propertyName) {
    try {//from   w  w  w  .  j  ava 2  s.  c  om
        Method propertyGetter = RequirementVersion.class.getMethod("get" + WordUtils.capitalize(propertyName));
        return ReflectionUtils.invokeMethod(propertyGetter, req);

    } catch (NoSuchMethodException e) {
        ReflectionUtils.handleReflectionException(e);
    }

    // this should never happen - the catch block rethows an exception
    return null;
}