Example usage for java.lang.reflect InvocationTargetException getCause

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

Introduction

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

Prototype

public Throwable getCause() 

Source Link

Document

Returns the cause of this exception (the thrown target exception, which may be null ).

Usage

From source file:com.github.lukaszbudnik.gugis.GugisInterceptor.java

public Observable<Try<Object>> executeBindings(final boolean allowFailure, Observable<Binding<Object>> bindings,
        final String methodName, final Object[] arguments) {

    Observable<Try<Object>> executedBindingsObservable = bindings.subscribeOn(Schedulers.newThread())
            .map(new Func1<Binding<Object>, Try<Object>>() {
                @Override/*from  w  w w .j  a v  a  2s .c o m*/
                public Try<Object> call(Binding<Object> binding) {
                    try {
                        Object component = binding.getProvider().get();
                        return new Success<Object>(MethodUtils.invokeMethod(component, methodName, arguments));
                    } catch (InvocationTargetException e) {
                        if (!allowFailure) {
                            // pass the original exception thrown
                            throw new GugisException(e.getCause());
                        }
                        return new Failure<Object>(e.getCause());
                    } catch (Exception e) {
                        throw new GugisException(e);
                    }
                }
            });

    return executedBindingsObservable;
}

From source file:org.lunarray.model.generation.vaadin.render.factories.form.vaadin.components.OperationOutputStrategy.java

/**
 * Execute the operation.//from  ww w . j  a  va  2s .  c om
 * 
 * @param descriptor
 *            The descriptor.
 * @param <R>
 *            The result type
 */
private <R> void execute(final ResultDescriptor<R> descriptor) {
    OperationOutputStrategy.LOGGER.debug("Invoking {}", descriptor);
    try {
        final R result = this.builder.execute(descriptor.getResultType());
        final OperationInvocationEvent<E, R> event = new OperationInvocationEvent<E, R>(this.descriptor,
                result);
        this.bus.handleEvent(event, this.builder);
    } catch (final ValueAccessException e) {
        OperationOutputStrategy.LOGGER.debug("Could not access value.", e);
        if (e.getCause() instanceof InvocationTargetException) {
            final InvocationTargetException ite = (InvocationTargetException) e.getCause();
            this.button.setComponentError(new UserError(ite.getCause().getMessage()));
        } else {
            this.button.setComponentError(new UserError(e.getMessage()));
        }
    } catch (final EventException e) {
        OperationOutputStrategy.LOGGER.warn("Could not process events.", e);
    }
}

From source file:com.zenesis.qx.remote.ProxyMethod.java

/**
 * Gets the prefetch value//  w ww  .  ja  va 2  s .com
 * @param self
 * @return
 */
public Object getPrefetchValue(Object self) {
    try {
        return method.invoke(self);
    } catch (InvocationTargetException e) {
        throw new IllegalStateException(
                "Error while invoking " + method + " on " + self + ": " + e.getCause().getMessage(),
                e.getCause());
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(
                "Error while invoking " + method + " on " + self + ": " + e.getMessage(), e);
    }
}

From source file:com.offbynull.coroutines.instrumenter.generators.GenericGeneratorsTest.java

@Test
public void mustCreateAndRunNestedSwitchStatements() throws Exception {
    // Augment signature
    methodNode.desc = Type.getMethodDescriptor(Type.getType(String.class),
            new Type[] { Type.INT_TYPE, Type.INT_TYPE });

    // Initialize variable table
    VariableTable varTable = new VariableTable(classNode, methodNode);
    Variable intVar1 = varTable.getArgument(1);
    Variable intVar2 = varTable.getArgument(2);

    // Update method logic
    /**/*w  ww.  ja v a 2 s  . c o  m*/
     * switch(arg1) {
     *    case 0:
     *        throw new RuntimeException("0");
     *    case 1:
     *         throw new RuntimeException("1");
     *    case 2:
     *         switch(arg2) {
     *             case 0:
     *                 throw new RuntimeException("0");
     *             case 1:
     *                 throw new RuntimeException("1");
     *             case 2:
     *                 return "OK!";
     *             default:
     *                 throw new RuntimeException("innerdefault")
     *         }
     *     default:
     *         throw new RuntimeException("default");
     * }
     */
    methodNode.instructions = tableSwitch(loadVar(intVar1), throwRuntimeException("default"), 0,
            throwRuntimeException("0"), throwRuntimeException("1"),
            tableSwitch(loadVar(intVar2), throwRuntimeException("innerdefault"), 0,
                    throwRuntimeException("inner0"), throwRuntimeException("inner1"),
                    GenericGenerators.returnValue(Type.getType(String.class), loadStringConst("OK!"))));

    // Write to JAR file + load up in classloader -- then execute tests
    try (URLClassLoader cl = createJarAndLoad(classNode)) {
        Object obj = cl.loadClass(STUB_CLASSNAME).newInstance();

        assertEquals("OK!", MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 2));

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 0, 0);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("0", ex.getCause().getMessage());
        }

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 2, 10);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("innerdefault", ex.getCause().getMessage());
        }

        try {
            MethodUtils.invokeMethod(obj, STUB_METHOD_NAME, 10, 0);
            fail();
        } catch (InvocationTargetException ex) {
            assertEquals("default", ex.getCause().getMessage());
        }
    }
}

From source file:org.jaffa.soa.dataaccess.DataTransformer.java

/**
 * Mould data from domain object and its related objects into a new JavaBean based
 * domain object graph, based on the defined mapping rules.
 *
 * @param source           Source object to mould data from, typically extends Persistent
 * @param target           Target object to mould data to, typically extends GraphDataObject
 * @param graph            The mapping class with the rules of how to map this source object
 * @param filter           Filter object that it is used to control what fields are populated or the target objects
 * @param objectPath       The path of this object being processed. This identifies possible parent
 *                         and/or indexed entries where this object is contained.
 * @param includeKeys      true if key fields should be included in results regardless of the filters
 * @param originalCriteria the original graph criteria.
 * @param handler          Possible bean handler to be used when processing this source object graph
 * @throws ApplicationExceptions Thrown if one or more application logic errors are generated during moulding
 * @throws FrameworkException    Thrown if any runtime moulding error has occured.
 *//*from   www .  j  a v a2  s.  co  m*/
public static void buildGraphFromDomain(Object source, Object target, GraphMapping graph, MappingFilter filter,
        String objectPath, boolean includeKeys, GraphCriteria originalCriteria, ITransformationHandler handler)
        throws ApplicationExceptions, FrameworkException {

    if (graph == null)
        graph = MappingFactory.getInstance(target);

    boolean useQueryDomain = graph.getQueryDomainClass() != null
            && source.getClass().isAssignableFrom(graph.getQueryDomainClass());

    //throw new InstantiationException("A GraphMapping must be supplied");
    if (filter == null)
        filter = MappingFilter.getInstance(graph);

    try {
        // get list of target fileds to populate
        String[] tFields = graph.getDataFieldNames();
        if (tFields != null && tFields.length != 0)
            for (int i = 0; i < tFields.length; i++) {
                // Try to map a source to a target
                String tName = tFields[i];
                String fullName = tName;
                if (objectPath != null)
                    fullName = objectPath + "." + fullName;

                if (filter == null || filter.isFieldIncluded(fullName)
                        || (includeKeys && graph.isKeyField(tName))) {
                    String sName = graph.getDomainFieldName(tName);
                    AccessibleObject tAccessibleObject = graph.getDataMutator(tName);
                    PropertyDescriptor tDesc = graph.getDataFieldDescriptor(tName);
                    PropertyDescriptor sDesc = useQueryDomain ? graph.getQueryDomainFieldDescriptor(tName)
                            : graph.getDomainFieldDescriptor(tName);

                    if (useQueryDomain && sDesc == null)
                        continue;

                    // Based on validation in GraphMapping, that there is a
                    // GraphObject descriptor with a setter, and a DO descriptor with a getter
                    if (sDesc == null)
                        log.error("No Getter for " + tName + " in path " + fullName);

                    // incase getter is not public, make it available
                    Method sm = sDesc.getReadMethod();
                    if (!sm.isAccessible())
                        sm.setAccessible(true);

                    // Set the value if the source and target are the same datatype
                    Class tClass = tDesc.getPropertyType();
                    Class sClass = sDesc.getPropertyType();
                    if (tClass.isAssignableFrom(sClass)) {
                        // Get the value being copied
                        Object sValue = sm.invoke(source, (Object[]) null);
                        setValue(tAccessibleObject, target, sValue);
                        if (log.isDebugEnabled())
                            log.debug("Set " + tName + " = " + sValue);

                        // See if there is a datatype mapper for these classes
                    } else if (DataTypeMapper.instance().isMappable(sClass, tClass)) {
                        // Get the value being copied
                        Object sValue = sm.invoke(source, (Object[]) null);
                        if (sValue != null) {
                            sValue = DataTypeMapper.instance().map(sValue, tClass);
                            if (log.isDebugEnabled())
                                log.debug("Set " + tName + " = " + sValue);
                        }
                        setValue(tAccessibleObject, target, sValue);

                        // See if target is a GraphObject, this could be a foreign object or one-to-one relationship...
                    } else if (GraphDataObject.class.isAssignableFrom(tClass)
                            && IPersistent.class.isAssignableFrom(sClass)) {
                        // Get the mapper for the related GraphObject, if it has keys, it must be a foriegn object
                        if (graph.isForeignField(tName)) {
                            // look at foreign key fields, and make sure they are not null
                            List foreignKeys = graph.getForeignKeys(tName);
                            List foreignKeyValues = new ArrayList();
                            boolean nullKey = false;
                            for (Iterator k = foreignKeys.iterator(); k.hasNext();) {
                                String doProp = (String) k.next();
                                Object value = null;
                                PropertyDescriptor doPd = graph.getRealDomainFieldDescriptor(doProp);
                                if (doPd != null && doPd.getReadMethod() != null) {
                                    Method m = doPd.getReadMethod();
                                    if (!m.isAccessible())
                                        m.setAccessible(true);
                                    value = m.invoke(source, new Object[] {});
                                    if (value == null)
                                        nullKey = true;
                                    foreignKeyValues.add(value);
                                } else {
                                    throw new TransformException(TransformException.INVALID_FK_MAPPING,
                                            objectPath, doProp, graph.getDomainClassShortName());
                                }
                            }
                            if (nullKey) {
                                if (log.isDebugEnabled())
                                    log.debug("Did not create skeleton object '" + tClass.getName()
                                            + "': one or more foreign key values missing.");
                            } else {
                                // Create the foreign object
                                if (log.isDebugEnabled())
                                    log.debug("Creating foreign object - " + tClass.getName());
                                Object newGDO = newGraphDataObject(tClass);
                                boolean createSkeleton = true;
                                // Only retrieve related domain object and introspect if need
                                if (filter.areSubFieldsIncluded(fullName)) {
                                    // read object and introspect all
                                    if (log.isDebugEnabled())
                                        log.debug("Read foreign object '" + fullName + "' and mold");
                                    try {
                                        Object sValue = sm.invoke(source, (Object[]) null);
                                        if (sValue != null) {
                                            DataTransformer.buildGraphFromDomain(sValue, newGDO, null, filter,
                                                    fullName, true, originalCriteria, handler);
                                            createSkeleton = false;
                                        }
                                    } catch (InvocationTargetException e) {
                                        // If the foreign object is not found, create the skeleton
                                        if (e.getCause() != null
                                                && e.getCause() instanceof InvalidForeignKeyException) {
                                            if (log.isDebugEnabled())
                                                log.debug(
                                                        "All foreign keys present, but foreign object does not exist",
                                                        e);
                                        } else
                                            throw e;
                                    }
                                }
                                if (createSkeleton) {
                                    // just set foreign keys from current object
                                    if (log.isDebugEnabled())
                                        log.debug("Set keys on skeleton foreign object only");
                                    GraphMapping graph2 = MappingFactory.getInstance(newGDO);
                                    Set keys = graph2.getKeyFields();
                                    if (keys == null || keys.size() != foreignKeyValues.size()) {
                                        throw new TransformException(TransformException.MISMATCH_FK_MAPPING,
                                                objectPath, target.getClass().getName(),
                                                newGDO.getClass().getName());
                                    }
                                    int k2 = 0;
                                    // Look through all the foreign keys on the skeleton object
                                    for (Iterator k = keys.iterator(); k.hasNext(); k2++) {
                                        String keyField = (String) k.next();
                                        Object keyValue = foreignKeyValues.get(k2);
                                        AccessibleObject accessibleObject = graph2.getDataMutator(keyField);
                                        if (accessibleObject != null) {
                                            setValue(accessibleObject, newGDO, keyValue);
                                        } else {
                                            throw new TransformException(TransformException.CANT_SET_KEY_FIELD,
                                                    objectPath, keyField, newGDO.getClass().getName());
                                        }
                                    }
                                }
                                setValue(tAccessibleObject, target, newGDO);
                                if (log.isDebugEnabled())
                                    log.debug("Set " + tName + " = " + newGDO);
                            }
                        } else {
                            // This is not a foreign object, must be a related object
                            if (filter.areSubFieldsIncluded(fullName)) {
                                // Create the related object
                                if (log.isDebugEnabled())
                                    log.debug("Creating One-To-One object - " + tClass.getName());
                                Object newGDO = newGraphDataObject(tClass);
                                // read object and introspect all
                                if (log.isDebugEnabled())
                                    log.debug("Read related object '" + fullName + "' and mold");
                                Object sValue = sm.invoke(source, (Object[]) null);
                                if (sValue != null) {
                                    DataTransformer.buildGraphFromDomain(sValue, newGDO, null, filter, fullName,
                                            false, originalCriteria, handler);
                                    setValue(tAccessibleObject, target, newGDO);
                                    if (log.isDebugEnabled())
                                        log.debug("Set " + tName + " = " + newGDO);
                                } else {
                                    if (log.isDebugEnabled())
                                        log.debug("Related object '" + fullName + "' not found. Ignore it!");
                                }
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("No subfields for object " + fullName
                                            + " included. Object not retrieved");
                            }
                        } //END-related object

                        // See if Target may be an array of GraphObject's
                    } else if (tClass.isArray()
                            && GraphDataObject.class.isAssignableFrom(tClass.getComponentType())
                            && filter.areSubFieldsIncluded(fullName)) {
                        if (log.isDebugEnabled())
                            log.debug("Target is an array of GraphObject's");
                        if (sClass.isArray() && IPersistent.class.isAssignableFrom(sClass.getComponentType())) {
                            if (log.isDebugEnabled()) {
                                log.debug("Source is an array of Persistent Objects");
                                log.debug("Read related objects '" + fullName + "' and mold");
                            }
                            Object[] sArray = findRelatedObjects(source, sClass, sm, handler, originalCriteria,
                                    fullName);
                            if (sArray != null && sArray.length > 0) {
                                Object[] tArray = (Object[]) Array.newInstance(tClass.getComponentType(),
                                        sArray.length);
                                if (log.isDebugEnabled())
                                    log.debug("Translate Array of Size " + sArray.length);
                                for (int j = 0; j < sArray.length; j++) {
                                    Object newGDO = newGraphDataObject(tClass.getComponentType());
                                    DataTransformer.buildGraphFromDomain(sArray[j], newGDO, null, filter,
                                            fullName, false, originalCriteria, handler);
                                    tArray[j] = newGDO;
                                    if (log.isDebugEnabled())
                                        log.debug("Add to array [" + j + "] : " + newGDO);
                                }
                                setValue(tAccessibleObject, target, tArray);
                                if (log.isDebugEnabled())
                                    log.debug("Set Array " + tName);
                            } else {
                                if (log.isDebugEnabled())
                                    log.debug("Source Array is empty! Do Nothing");
                            }
                        } // source is DO array

                        // Error... No way to map property
                    } else {
                        String err = "Can't Mold Property " + fullName + " from " + sClass.getName() + " to "
                                + tClass.getName();
                        log.error(err);
                        throw new RuntimeException(err);
                    }
                } // is included in filtered fields
            }

        // Load flex fields
        // By default all the domain-mapped flex fields will be loaded; unless excluded by a rule
        if (source instanceof IFlexFields && target instanceof IFlexFields) {
            String fullName = (objectPath != null ? objectPath + '.' : "") + "flexBean";
            if (filter == null || filter.isFieldIncluded(fullName)) {
                if (log.isDebugEnabled())
                    log.debug("Loading FlexBean " + fullName);
                FlexBean sFlexBean = ((IFlexFields) source).getFlexBean();
                FlexBean tFlexBean = ((IFlexFields) target).getFlexBean();
                if (sFlexBean != null && tFlexBean != null) {
                    for (DynaProperty flexProperty : sFlexBean.getDynaClass().getDynaProperties()) {
                        String name = flexProperty.getName();
                        Boolean include = filter.includeField(fullName + '.' + name);
                        if (include != null ? include
                                : ((FlexProperty) flexProperty).getFlexInfo()
                                        .getProperty("domain-mapping") != null) {
                            Object value = sFlexBean.get(name);
                            if (value != null) {
                                if (log.isDebugEnabled())
                                    log.debug("Loaded flex field '" + name + '=' + value + '\'');
                                tFlexBean.set(name, value);
                            }
                        }
                    }
                }
            }
        }

        // Clear changed fields on updated GraphObject
        if (target != null && target instanceof GraphDataObject)
            ((GraphDataObject) target).clearChanges();

        // Invoke the handler
        if (handler != null) {
            if (log.isDebugEnabled()) {
                log.debug("Invoking the endBeanLoad on the handler");
            }
            for (ITransformationHandler transformationHandler : handler.getTransformationHandlers()) {
                transformationHandler.endBeanLoad(objectPath, source, target, filter, originalCriteria);
            }
        }

    } catch (ApplicationException e) {
        throw new ApplicationExceptions(e);
    } catch (IllegalAccessException e) {
        TransformException me = new TransformException(TransformException.ACCESS_ERROR, objectPath,
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    } catch (InvocationTargetException e) {
        ApplicationExceptions appExps = ExceptionHelper.extractApplicationExceptions(e);
        if (appExps != null)
            throw appExps;
        FrameworkException fe = ExceptionHelper.extractFrameworkException(e);
        if (fe != null)
            throw fe;
        TransformException me = new TransformException(TransformException.INVOCATION_ERROR, objectPath, e);
        log.error(me.getLocalizedMessage(), me.getCause());
        throw me;
    } catch (InstantiationException e) {
        TransformException me = new TransformException(TransformException.INSTANTICATION_ERROR, objectPath,
                e.getMessage());
        log.error(me.getLocalizedMessage(), e);
        throw me;
    }
}

From source file:de.blizzy.backup.check.CheckRun.java

public void runCheck() {
    boolean canceled = false;
    boolean errors = false;
    try {/*from   www . j  a  v  a2 s .  c o  m*/
        ProgressMonitorDialog dlg = new ProgressMonitorDialog(parentShell);
        dlg.run(true, true, this);
    } catch (InvocationTargetException e) {
        BackupPlugin.getDefault().logError("error while checking backup integrity", e.getCause()); //$NON-NLS-1$
        errors = true;
    } catch (RuntimeException e) {
        BackupPlugin.getDefault().logError("error while checking backup integrity", e); //$NON-NLS-1$
        errors = true;
    } catch (InterruptedException e) {
        canceled = true;
    }

    if (!canceled) {
        if (errors) {
            MessageDialog.openError(parentShell, Messages.Title_BackupIntegrityCheck,
                    Messages.ErrorsWhileCheckingBackup);
        } else {
            if (backupOk) {
                MessageDialog.openInformation(parentShell, Messages.Title_BackupIntegrityCheck,
                        Messages.BackupIntegrityIntact);
            } else {
                MessageDialog.openError(parentShell, Messages.Title_BackupIntegrityCheck,
                        Messages.BackupIntegrityNotIntact);
            }
        }
    }
}

From source file:com.liusoft.dlog4j.action.ActionExtend.java

/**
 * Action???????? //from w  w  w  .ja  va2s . c o m
 * 1.??eventSubmit_XxxxdoXxxx
 * 2.?__method?do
 */
public final ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {
    ActionForward af = beforeExecute(mapping, form, req, res);
    if (af != null)
        return af;

    String param = null;
    String value = null;

    String __method = req.getParameter(METHOD_IDENT_PARAM);
    if (StringUtils.isNotBlank(__method)) {
        param = METHOD_PREFIX + __method;
    } else {
        for (Enumeration params = req.getParameterNames(); params.hasMoreElements();) {
            String t_param = (String) params.nextElement();
            if (t_param.startsWith(SUBMIT_BUTTON_PREFIX)) {
                value = req.getParameter(t_param);
                param = METHOD_PREFIX + t_param.substring(SUBMIT_BUTTON_PREFIX.length());
                break;
            }
        }
    }

    if (param == null)
        param = "doDefault";

    try {
        return callActionMethod(mapping, form, req, res, param, value);
    } catch (InvocationTargetException e) {
        Throwable t = e.getCause();
        if (t instanceof IllegalAccessException) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }
        log.error("Exception occur when calling " + param + " in action:" + getClass().getName(), t);
        if (t instanceof Exception)
            throw (Exception) t;
        else
            throw new Exception(t);
    } catch (NoSuchMethodException e) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return null;
    } finally {
        afterExecute(mapping, form, req, res);
    }
}

From source file:com.orange.mmp.api.helpers.DefaultApiContainer.java

public Object invokeApi(Api api, String methodName, Object... params) throws MMPApiException {
    Object apiImplementation = this.getApiImplementation(api);
    Method method = this.getApiMethod(api, methodName);

    try {//  w w w . j  a v a 2s  .  c  om
        return method.invoke(apiImplementation, params);
    } catch (IllegalArgumentException iarge) {
        throw new MMPApiException(iarge);
    } catch (IllegalAccessException iae) {
        throw new MMPApiException(iae);
    } catch (InvocationTargetException ite) {
        throw new MMPApiException(ite.getCause());
    }
}

From source file:org.callimachusproject.setup.WebappArchiveImporter.java

private boolean deleteComponents(String folder) {
    try {/*from  w  ww . j  a  va  2  s .com*/
        try {
            repository.setSchemaGraphType(webapp + SCHEMA_GRAPH);
            repository.setCompileRepository(true);
            ObjectConnection con = repository.getConnection();
            try {
                con.begin();
                RDFObject obj = (RDFObject) con.getObject(folder);
                Method DeleteComponents = findDeleteComponents(obj);
                try {
                    logger.info("Removing {}", folder);
                    invokeAndRemove(DeleteComponents, obj, con);
                    con.commit();
                    return true;
                } catch (InvocationTargetException e) {
                    try {
                        throw e.getCause();
                    } catch (Exception cause) {
                        logger.warn(cause.toString());
                    } catch (Error cause) {
                        logger.warn(cause.toString());
                    } catch (Throwable cause) {
                        logger.warn(cause.toString());
                    }
                    con.rollback();
                    return false;
                }
            } catch (IllegalAccessException e) {
                logger.debug(e.toString());
            } catch (NoSuchMethodException e) {
                logger.debug(e.toString());
            } finally {
                con.rollback();
                repository.setCompileRepository(false);
                con.close();
            }
        } finally {
            repository.setCompileRepository(false);
        }
    } catch (RDFObjectException e) {
        logger.debug(e.toString());
    } catch (OpenRDFException e) {
        logger.debug(e.toString());
    }
    return false;
}