Example usage for java.lang.reflect InvocationTargetException getTargetException

List of usage examples for java.lang.reflect InvocationTargetException getTargetException

Introduction

In this page you can find the example usage for java.lang.reflect InvocationTargetException getTargetException.

Prototype

public Throwable getTargetException() 

Source Link

Document

Get the thrown target exception.

Usage

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

public void _setIndexedProperty(final Object bean, final String name, final int index, final Object value)
        throws Exception {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }//  www .java2  s  .co m
    if (name == null || name.length() == 0) {
        if (bean.getClass().isArray()) {
            Array.set(bean, index, value);
            return;
        } else if (bean instanceof List) {
            final List<Object> list = toObjectList(bean);
            list.set(index, value);
            return;
        }
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'");
    }

    if (name.startsWith("@")) {
        Object f = FieldUtils.readField(bean, name.substring(1));
        if (null == f)
            throw new NestedNullException();
        if (f.getClass().isArray()) {
            Array.set(f, index, value);
            return;
        } else if (f instanceof List) {
            final List<Object> list = toObjectList(f);
            list.set(index, value);
            return;
        }
        return;
    }
    // Retrieve the property descriptor for the specified property
    final PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
    if (descriptor == null) {
        throw new NoSuchMethodException(
                "Unknown property '" + name + "' on bean class '" + bean.getClass() + "'");
    }

    // Call the indexed setter method if there is one
    if (descriptor instanceof IndexedPropertyDescriptor) {
        Method writeMethod = ((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod();
        writeMethod = MethodUtils.getAccessibleMethod(bean.getClass(), writeMethod);
        if (writeMethod != null) {
            final Object[] subscript = new Object[2];
            subscript[0] = new Integer(index);
            subscript[1] = value;
            try {
                if (log.isTraceEnabled()) {
                    final String valueClassName = value == null ? "<null>" : value.getClass().getName();
                    log.trace("setSimpleProperty: Invoking method " + writeMethod + " with index=" + index
                            + ", value=" + value + " (class " + valueClassName + ")");
                }
                invokeMethod(writeMethod, bean, subscript);
            } catch (final InvocationTargetException e) {
                if (e.getTargetException() instanceof IndexOutOfBoundsException) {
                    throw (IndexOutOfBoundsException) e.getTargetException();
                } else {
                    throw e;
                }
            }
            return;
        }
    }

    // Otherwise, the underlying property must be an array or a list
    final Method readMethod = getReadMethod(bean.getClass(), descriptor);
    if (readMethod == null) {
        throw new NoSuchMethodException(
                "Property '" + name + "' has no getter method on bean class '" + bean.getClass() + "'");
    }

    // Call the property getter to get the array or list
    final Object array = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
    if (!array.getClass().isArray()) {
        if (array instanceof List) {
            // Modify the specified value in the List
            final List<Object> list = toObjectList(array);
            list.set(index, value);
        } else {
            throw new IllegalArgumentException(
                    "Property '" + name + "' is not indexed on bean class '" + bean.getClass() + "'");
        }
    } else {
        // Modify the specified value in the array
        Array.set(array, index, value);
    }

}

From source file:AppearanceTest.java

public void actionPerformed(ActionEvent event) {
    // (primitive) menu command dispatch
    Class classObject = getClass();

    Method[] methodArray = classObject.getMethods();

    for (int n = methodArray.length - 1; n >= 0; n--) {
        if (("on" + event.getActionCommand()).equals(methodArray[n].getName())) {
            try {
                methodArray[n].invoke(this, null);
            } catch (InvocationTargetException ie) {
                System.err.println("Warning. Menu handler threw exception: " + ie.getTargetException());
            } catch (Exception e) {
                System.err.println("Warning. Menu dispatch exception: " + e);
            }/*w ww. j a  va  2 s  .com*/

            return;
        }
    }
}

From source file:com.netspective.commons.xdm.XmlDataModelSchema.java

protected Object createElement(XdmParseContext pc, String alternateClassName, Object element,
        String elementName) throws DataModelException, UnsupportedElementException {
    try {//from www  . j  a v a 2s  . c  om
        if (alternateClassName != null) {
            Class cls = null;
            try {
                cls = Class.forName(alternateClassName);
            } catch (ClassNotFoundException e) {
                pc.addError("Class '" + alternateClassName + "' for element '" + elementName + "' not found at "
                        + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber() + ". "
                        + e.getMessage());
                log.error(e);
                if (pc.isThrowErrorException())
                    throw new DataModelException(pc, e);
                else {
                    NestedCreator nc = (NestedCreator) nestedCreators.get(elementName);
                    if (nc != null)
                        return nc.create(element);
                }
            }

            NestedAltClassCreator nac = (NestedAltClassCreator) nestedAltClassNameCreators.get(elementName);
            if (nac != null)
                return nac.create(element, cls);
            else {
                // check to make sure that either a storer or creator is available to ensure it's a valid tag
                if (nestedCreators.get(elementName) != null || nestedStorers.get(elementName) != null)
                    return cls.newInstance();

                UnsupportedElementException e = new UnsupportedElementException(this, pc, element, elementName);
                if (pc != null) {
                    pc.addError(e);
                    if (pc.isThrowErrorException())
                        throw e;
                    else
                        return null;
                } else
                    return null;
            }
        } else {
            NestedCreator nc = (NestedCreator) nestedCreators.get(elementName);
            if (nc != null)
                return nc.create(element);
        }
    } catch (InvocationTargetException ite) {
        pc.addError("Could not create class '" + alternateClassName + "' for element '" + elementName + "' at "
                + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber() + ": "
                + ite.getMessage());
        log.error(ite);
        if (pc.isThrowErrorException()) {
            Throwable t = ite.getTargetException();
            if (t instanceof DataModelException) {
                throw (DataModelException) t;
            }
            throw new DataModelException(pc, t);
        }
    } catch (Exception e) {
        pc.addError("Could not create class '" + alternateClassName + "' for element '" + elementName + "' at "
                + pc.getLocator().getSystemId() + " line " + pc.getLocator().getLineNumber() + ": "
                + e.getMessage());
        log.error(e);
        if (pc.isThrowErrorException())
            throw new DataModelException(pc, e);
    }

    // if the element is being defined as a sub-element but has an attribute of the same name, it's a convenience attribute setter
    AttributeSetter as = (AttributeSetter) attributeSetters.get(elementName);
    if (as != null)
        return element;
    else {
        // see if we're trying to set a named flag as a sub-element
        for (Iterator i = flagsAttributeAccessors.entrySet().iterator(); i.hasNext();) {
            Map.Entry entry = (Map.Entry) i.next();
            AttributeAccessor accessor = (AttributeAccessor) entry.getValue();
            Object returnVal = null;
            try {
                returnVal = accessor.get(pc, element);
            } catch (Exception e) {
            }

            if (returnVal instanceof XdmBitmaskedFlagsAttribute)
                return element;
        }

        UnsupportedElementException e = new UnsupportedElementException(this, pc, element, elementName);
        if (pc != null) {
            pc.addError(e);
            if (pc.isThrowErrorException())
                throw e;
            else
                return null;
        } else
            return null;
    }
}

From source file:net.wastl.webmail.server.WebMailServer.java

protected void initStorage() throws UnavailableException {
    /* Storage API */
    try {//from   ww w  .  j ava  2  s  .  c  o m
        Class storage_api = Class.forName(config.getProperty("webmail.storage"));

        Class[] tmp = new Class[1];
        tmp[0] = Class.forName("net.wastl.webmail.server.WebMailServer");
        Constructor cons = storage_api.getConstructor(tmp);

        Object[] sargs = new Object[1];
        sargs[0] = this;

        storage = (Storage) cons.newInstance(sargs);

    } catch (InvocationTargetException e) {
        log.fatal("Could not initialize. Exiting now!  Nested exc:", e.getTargetException());
        throw new UnavailableException(e.getMessage());
    } catch (Exception e) {
        log.fatal("Could not initialize. Exiting now!", e);
        throw new UnavailableException(e.getMessage());
    }
}

From source file:net.yck.wkrdb.common.shared.PropertyConverter.java

/**
 * Tries to convert the specified object into a number object. This method
 * is used by the conversion methods for number types. Note that the return
 * value is not in always of the specified target class, but only if a new
 * object has to be created./* w  w w. ja  va  2 s  .  c o  m*/
 *
 * @param value
 *            the value to be converted (must not be <b>null</b>)
 * @param targetClass
 *            the target class of the conversion (must be derived from
 *            {@code java.lang.Number})
 * @return the converted number
 * @throws ConversionException
 *             if the object cannot be converted
 */
static Number toNumber(Object value, Class<?> targetClass) throws ConversionException {
    if (value instanceof Number) {
        return (Number) value;
    } else {
        String str = value.toString();
        if (str.startsWith(HEX_PREFIX)) {
            try {
                return new BigInteger(str.substring(HEX_PREFIX.length()), HEX_RADIX);
            } catch (NumberFormatException nex) {
                throw new ConversionException(
                        "Could not convert " + str + " to " + targetClass.getName() + "! Invalid hex number.",
                        nex);
            }
        }

        if (str.startsWith(BIN_PREFIX)) {
            try {
                return new BigInteger(str.substring(BIN_PREFIX.length()), BIN_RADIX);
            } catch (NumberFormatException nex) {
                throw new ConversionException("Could not convert " + str + " to " + targetClass.getName()
                        + "! Invalid binary number.", nex);
            }
        }

        try {
            Constructor<?> constr = targetClass.getConstructor(CONSTR_ARGS);
            return (Number) constr.newInstance(str);
        } catch (InvocationTargetException itex) {
            throw new ConversionException("Could not convert " + str + " to " + targetClass.getName(),
                    itex.getTargetException());
        } catch (Exception ex) {
            // Treat all possible exceptions the same way
            throw new ConversionException(
                    "Conversion error when trying to convert " + str + " to " + targetClass.getName(), ex);
        }
    }
}

From source file:net.ymate.platform.commons.util.RuntimeUtils.java

public static Throwable unwrapThrow(Throwable e) {
    if (e == null) {
        return null;
    }/*  w w w .  java  2s  . com*/
    if (e instanceof InvocationTargetException) {
        InvocationTargetException itE = (InvocationTargetException) e;
        if (itE.getTargetException() != null) {
            return unwrapThrow(itE.getTargetException());
        }
    }
    if (e.getCause() != null) {
        return unwrapThrow(e.getCause());
    }
    return e;
}

From source file:nl.strohalm.cyclos.spring.ServiceSecurityProxyInvocationHandler.java

@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    try {//from ww w. j  av a  2  s.co  m
        try {
            return method.invoke(bean, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
    } catch (Throwable t) {
        CurrentTransactionData.setError(t);
        throw t;
    }
}

From source file:opendial.DialogueSystem.java

/**
 * Attaches the module to the dialogue system.
 * //from w ww.ja v a2 s  .  c  o  m
 * @param module the module class to instantiate
 */
public <T extends Module> void attachModule(Class<T> module) {
    try {
        Constructor<T> constructor = module.getConstructor(DialogueSystem.class);
        attachModule(constructor.newInstance(this));
        recordComment("Module " + module.getSimpleName() + " successfully attached");
    } catch (InvocationTargetException e) {
        log.warning("cannot attach module: " + e.getTargetException());
        e.printStackTrace();
        recordComment("cannot attach module: " + e.getTargetException());
    } catch (Exception e) {
        log.warning("cannot attach module of class " + module.getCanonicalName() + ": " + e);
    }
}

From source file:org.acmsl.commons.regexpplugin.RegexpManager.java

/**
 * Returns the thread context class loader if available.
 * The thread context class loader is available for JDK 1.2
 * or later, if certain security conditions are met.
 * Note: This logic is adapted from Commons-Logging.
 * @param reflectionUtils the <code>ReflectionUtils</code> instance.
 * @return the class loader.//from  ww w.  j  av a 2s  .  co  m
 * @throws RegexpPluginMisconfiguredException if a suitable class loader
 * cannot be identified.
 */
@NotNull
protected ClassLoader getContextClassLoader(@NotNull final ReflectionUtils reflectionUtils)
        throws RegexpPluginMisconfiguredException {
    @NotNull
    final ClassLoader result;

    try {
        result = reflectionUtils.getContextClassLoader();
    } catch (final IllegalAccessException illegalAccessException) {
        throw new RegexpPluginMisconfiguredException("unexpected.illegalaccessexception",
                illegalAccessException);
    } catch (final InvocationTargetException invocationTargetException) {
        throw new RegexpPluginMisconfiguredException("unexpected.invocationtargetexception",
                invocationTargetException.getTargetException());
    }

    // Return the selected class loader
    return result;
}

From source file:org.acmsl.commons.utils.ReflectionUtils.java

/**
 * Returns the thread context class loader if available.
 * The thread context class loader is available for JDK 1.2
 * or later, if certain security conditions are met.
 * Note: This logic is adapted from Commons-Logging.
 * @return the class loader.//from ww w .ja  va  2  s.  c  om
 * @throws IllegalAccessException when trying to access
 * <code>Thread.getContextClassLoader()</code> via reflection.
 * @throws InvocationTargetException when trying to access
 * <code>Thread.getContextClassLoader()</code> via reflection, and
 * the target exception is not a <code>SecurityException</code>..
 */
@NotNull
public ClassLoader getContextClassLoader() throws IllegalAccessException, InvocationTargetException {
    @Nullable
    ClassLoader result = null;

    try {
        // Are we running on a JDK 1.2 or later system?
        @NotNull
        final Method t_Method = Thread.class.getMethod("getContextClassLoader", (Class<?>) null);

        // Get the thread context class loader (if there is one)
        try {
            result = (ClassLoader) t_Method.invoke(Thread.currentThread(), (Class<?>) null);
        } catch (final InvocationTargetException invocationTargetException) {
            /**
             * InvocationTargetException is thrown by 'invoke' when
             * the method being invoked (getContextClassLoader) throws
             * an exception.
             *
             * getContextClassLoader() throws SecurityException when
             * the context class loader isn't an ancestor of the
             * calling class's class loader, or if security
             * permissions are restricted.
             *
             * In the first case (not related), we want to ignore and
             * keep going.  We cannot help but also ignore the second
             * with the logic below, but other calls elsewhere (to
             * obtain a class loader) will trigger this exception where
             * we can make a distinction.
             */
            if (invocationTargetException.getTargetException() instanceof SecurityException) {
                LogFactory.getLog(ReflectionUtils.class).info("Could not retrieve context class loader.",
                        invocationTargetException);
            } else {
                throw invocationTargetException;
            }
        }
    } catch (final NoSuchMethodException noSuchMethodException) {
        // Assume we are running on JDK 1.1
        result = ReflectionUtils.class.getClassLoader();
    }
    if (result == null) {
        result = ReflectionUtils.class.getClassLoader();
    }

    // Return the selected class loader
    return result;
}