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:org.cloudata.core.common.testhelper.ProxyExceptionHelper.java

public static void handleException(UndeclaredThrowableException e, Log LOG) throws IOException {
    if (e.getUndeclaredThrowable() instanceof InvocationTargetException) {
        InvocationTargetException ex = ((InvocationTargetException) e.getUndeclaredThrowable());
        if (ex.getTargetException() instanceof IOException) {
            throw (IOException) ex.getTargetException();
        } else {/*  w  w  w.j a v a  2  s  .co m*/
            LOG.fatal("Unexpected exception is occurred", ex.getTargetException());
            throw new IOException("Unexpected exception is occurred : " + e, e);
        }
    } else {
        LOG.fatal("Unexpected exception is occurred", e);
        throw new IOException("Unexpected exception is occurred : " + e, e);
    }

}

From source file:org.cloudifysource.dsl.internal.BaseDslScript.java

private void validateObject(final Object obj) throws DSLValidationException {

    final Method[] methods = obj.getClass().getDeclaredMethods();
    for (final Method method : methods) {
        if (method.getAnnotation(DSLValidation.class) != null) {
            final boolean accessible = method.isAccessible();
            try {
                @SuppressWarnings("unchecked")
                final Map<Object, Object> currentVars = this.getBinding().getVariables();
                final DSLValidationContext validationContext = new DSLValidationContext();
                validationContext.setFilePath((String) currentVars.get(DSLUtils.DSL_FILE_PATH_PROPERTY_NAME));
                method.setAccessible(true);
                method.invoke(obj, validationContext);

            } catch (final InvocationTargetException e) {
                throw new DSLValidationException(e.getTargetException().getMessage(), e.getTargetException());
            } catch (final Exception e) {
                throw new DSLValidationException("Failed to execute DSL validation: " + e.getMessage(), e);

            } finally {
                method.setAccessible(accessible);
            }/* w w  w . j  a  v  a2s  . c  o  m*/
        }
    }

}

From source file:org.codehaus.enunciate.modules.rest.RESTOperation.java

/**
 * Invokes the operation with the specified proper noun, adjectives, and noun value on the given endpoint.
 *
 * @param properNoun The value for the proper noun.
 * @param contextParameters The context parametesr for this operation.
 * @param adjectives The value for the adjectives.
 * @param nounValue  The value for the noun.
 * @param endpoint The endpoint on which to invoke the operation.
 * @return The result of the invocation.  If the invocation has no return type (void), returns null.
 * @throws Exception if any problems occur.
 *///from  w w  w  .  j  ava 2s .  c om
public Object invoke(Object properNoun, Map<String, Object> contextParameters, Map<String, Object> adjectives,
        Object nounValue, Object endpoint) throws Exception {
    Class[] parameterTypes = this.method.getParameterTypes();
    Object[] parameters = new Object[parameterTypes.length];
    if (properNounIndex > -1) {
        parameters[properNounIndex] = properNoun;
    }

    if (nounValueIndex > -1) {
        if ((nounValue != null) && (Collection.class.isAssignableFrom(parameterTypes[nounValueIndex]))) {
            //convert the noun value back into a collection...
            nounValue = convertToCollection(nounValue, parameterTypes[nounValueIndex]);
        }

        parameters[nounValueIndex] = nounValue;
    }

    if (contentTypeParameterIndex > -1) {
        parameters[contentTypeParameterIndex] = getContentType();
    }

    for (String adjective : adjectiveIndices.keySet()) {
        Object adjectiveValue = adjectives.get(adjective);
        Integer index = adjectiveIndices.get(adjective);
        if ((adjectiveValue != null) && (Collection.class.isAssignableFrom(parameterTypes[index]))) {
            //convert the array back into a collection...
            adjectiveValue = convertToCollection(adjectiveValue, parameterTypes[index]);
        }

        parameters[index] = adjectiveValue;
    }

    for (String contextParameterName : contextParameterIndices.keySet()) {
        parameters[contextParameterIndices.get(contextParameterName)] = contextParameters
                .get(contextParameterName);
    }

    try {
        return this.method.invoke(endpoint, parameters);
    } catch (InvocationTargetException e) {
        Throwable target = e.getTargetException();
        if (target instanceof Error) {
            throw (Error) target;
        }

        throw (Exception) target;
    }
}

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

public Object invoke(final Object proxy, final Method thisMethod, final Method proceed, final Object[] args)
        throws Throwable {
    Object result = groovyObjectMethodHandler.handleInvocation(proxy, thisMethod, args);
    if (groovyObjectMethodHandler.wasHandled(result)) {
        return result;
    }/*  ww  w.j  a  v  a2s .  c  o m*/

    if (constructed) {
        try {
            result = invoke(thisMethod, args, proxy);
        } catch (Throwable t) {
            throw new Exception(t.getCause());
        }
        if (result == INVOKE_IMPLEMENTATION) {
            Object target = getImplementation();
            final Object returnValue;
            try {
                if (ReflectHelper.isPublic(persistentClass, thisMethod)) {
                    if (!thisMethod.getDeclaringClass().isInstance(target)) {
                        throw new ClassCastException(target.getClass().getName());
                    }
                    returnValue = thisMethod.invoke(target, args);
                } else {
                    if (!thisMethod.isAccessible()) {
                        thisMethod.setAccessible(true);
                    }
                    returnValue = thisMethod.invoke(target, args);
                }
                return returnValue == target ? proxy : returnValue;
            } catch (InvocationTargetException ite) {
                throw ite.getTargetException();
            }
        }
        return result;
    }

    // while constructor is running
    if (thisMethod.getName().equals("getHibernateLazyInitializer")) {
        return this;
    }

    return proceed.invoke(proxy, args);
}

From source file:org.codehaus.mojo.macker.CommandLineFile.java

public static void main(String[] args) throws Exception {
    if (args.length == 0 || args.length > 2) {
        System.err.println("Usage: CommandLineFile <main class> [command line arguments file]");
        System.exit(1);/*from  ww  w. j av a  2  s  . c  om*/
    }

    String className = args[0];
    Class clazz = Class.forName(className);
    Method main = clazz.getMethod("main", new Class[] { String[].class });

    List/*<String>*/ lines = new ArrayList/*<String>*/();
    if (args.length == 2) {
        Reader in = new InputStreamReader(new FileInputStream(args[1]), "UTF-8");
        try {
            lines = IOUtils.readLines(in);
        } finally {
            in.close();
        }
    }

    try {
        main.invoke(null, new Object[] { lines.toArray(new String[lines.size()]) });
    } catch (InvocationTargetException ex) {
        Throwable cause = ex.getTargetException();
        if (cause instanceof Error) {
            throw (Error) cause;
        }
        throw (Exception) cause;
    }
}

From source file:org.commonjava.indy.tools.cache.Main.java

public static void main(String[] args) {
    Thread.currentThread().setUncaughtExceptionHandler((thread, error) -> {
        if (error instanceof InvocationTargetException) {
            final InvocationTargetException ite = (InvocationTargetException) error;
            System.err.println(/*from   w w  w . j  a v a2s. c o  m*/
                    "In: " + thread.getName() + "(" + thread.getId() + "), caught InvocationTargetException:");
            ite.getTargetException().printStackTrace();

            System.err.println("...via:");
            error.printStackTrace();
        } else {
            System.err.println("In: " + thread.getName() + "(" + thread.getId() + ") Uncaught error:");
            error.printStackTrace();
        }
    });

    MigrationOptions options = new MigrationOptions();
    try {
        if (options.parseArgs(args)) {
            try {
                int result = new Main().run(options);
                if (result != 0) {
                    System.exit(result);
                }
            } catch (final IndyBootException e) {
                System.err.printf("ERROR INITIALIZING BOOTER: %s", e.getMessage());
                System.exit(ERR_CANT_INIT_BOOTER);
            }
        }
    } catch (final IndyBootException e) {
        System.err.printf("ERROR: %s", e.getMessage());
        System.exit(ERR_CANT_PARSE_ARGS);
    }
}

From source file:org.datanucleus.store.rdbms.ConnectionFactoryImpl.java

/**
 * Method to initialise the datasource(s) used by this connection factory.
 * Searches initially for a provided DataSource, then if not found, for JNDI DataSource(s), and finally
 * for the DataSource at a connection URL.
 * @param connDS Factory data source object
 * @param connJNDI DataSource JNDI name(s)
 * @param connURL URL for connections//  w  ww . j a  va  2 s  .  c o m
 */
private void initialiseDataSources(Object connDS, String connJNDI, String resourceType,
        String requiredPoolingType, String connURL) {
    if (connDS != null) {
        if (!(connDS instanceof DataSource) && !(connDS instanceof XADataSource)) {
            throw new UnsupportedConnectionFactoryException(connDS);
        }
        dataSource = new DataSource[1];
        dataSource[0] = connDS;
    } else if (connJNDI != null) {
        String[] connectionFactoryNames = StringUtils.split(connJNDI, ",");
        dataSource = new DataSource[connectionFactoryNames.length];
        for (int i = 0; i < connectionFactoryNames.length; i++) {
            dataSource[i] = lookupDataSource(connectionFactoryNames[i]);
        }
    } else if (connURL != null) {
        dataSource = new DataSource[1];
        String poolingType = calculatePoolingType(requiredPoolingType);

        // User has requested internal database connection pooling so check the registered plugins
        try {
            // Create the DataSource to be used
            DataNucleusDataSourceFactory dataSourceFactory = (DataNucleusDataSourceFactory) storeMgr
                    .getNucleusContext().getPluginManager()
                    .createExecutableExtension("org.datanucleus.store.rdbms.datasource", "name", poolingType,
                            "class-name", null, null);
            if (dataSourceFactory == null) {
                // User has specified a pool plugin that has not registered
                throw new NucleusUserException(LOCALISER_RDBMS.msg("047003", poolingType)).setFatal();
            }

            // Create the DataNucleusDataSourceFactory
            dataSource[0] = dataSourceFactory.makePooledDataSource(storeMgr);
            if (NucleusLogger.CONNECTION.isDebugEnabled()) {
                NucleusLogger.CONNECTION.debug(LOCALISER_RDBMS.msg("047008", resourceType, poolingType));
            }
        } catch (ClassNotFoundException cnfe) {
            throw new NucleusUserException(LOCALISER_RDBMS.msg("047003", poolingType), cnfe).setFatal();
        } catch (Exception e) {
            if (e instanceof InvocationTargetException) {
                InvocationTargetException ite = (InvocationTargetException) e;
                throw new NucleusException(
                        LOCALISER_RDBMS.msg("047004", poolingType, ite.getTargetException().getMessage()),
                        ite.getTargetException()).setFatal();
            } else {
                throw new NucleusException(LOCALISER_RDBMS.msg("047004", poolingType, e.getMessage()), e)
                        .setFatal();
            }
        }
    }
}

From source file:org.dhatim.cdr.annotation.Configurator.java

private static <U> void setMember(Member member, U instance, Object value) {
    try {/*from  ww w .j a v a 2s .c  o m*/
        if (member instanceof Field) {
            ClassUtil.setField((Field) member, instance, value);
        } else {
            try {
                setMethod((Method) member, instance, value);
            } catch (InvocationTargetException e) {
                throw new SmooksConfigurationException(
                        "Failed to set paramater configuration value on '" + getLongMemberName(member) + "'.",
                        e.getTargetException());
            }
        }
    } catch (IllegalAccessException e) {
        throw new SmooksConfigurationException(
                "Failed to set paramater configuration value on '" + getLongMemberName(member) + "'.", e);
    }
}

From source file:org.directwebremoting.filter.AuditLogAjaxFilter.java

public Object doFilter(Object obj, Method method, Object[] params, AjaxFilterChain chain) throws Exception {
    StringBuilder call = new StringBuilder();
    call.append(obj.getClass().getSimpleName());
    call.append('.');
    call.append(method.getName());/*ww w  . j  av  a2 s .c  o  m*/
    call.append('(');
    for (int i = 0; i < params.length; i++) {
        if (i != 0) {
            call.append(", ");
        }
        call.append(toString(params[i]));
    }
    call.append(')');

    try {
        Object reply = chain.doFilter(obj, method, params);
        log.info(call.toString() + " = " + toString(reply));
        return reply;
    } catch (InvocationTargetException ex) {
        log.info(call.toString() + " = " + ex.getTargetException(), ex.getTargetException());
        throw ex;
    } catch (Exception ex) {
        log.info(call.toString() + " = " + ex, ex);
        throw ex;
    } catch (Error ex) {
        log.warn(call.toString() + " = " + ex, ex);
        throw ex;
    }
}

From source file:org.directwebremoting.util.Continuation.java

/**
 * Unwrap an InvocationTargetException//from  w  w w  .j a v  a2 s .c o  m
 * @param ex The exception to unwrap
 * @return Nothing. This method will not complete normally
 * @throws Exception If reflection breaks
 */
private static Object rethrowWithoutWrapper(InvocationTargetException ex) throws Exception {
    Throwable target = ex.getTargetException();
    if (target instanceof Exception) {
        throw (Exception) target;
    }

    if (target instanceof Error) {
        throw (Error) target;
    }

    throw ex;
}