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:org.broadleafcommerce.common.extension.ExtensionManager.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    boolean notHandled = true;
    for (ExtensionHandler handler : getHandlers()) {
        try {/*from www .  ja va2  s . c  om*/
            if (handler.isEnabled()) {
                ExtensionResultStatusType result = (ExtensionResultStatusType) method.invoke(handler, args);
                if (!ExtensionResultStatusType.NOT_HANDLED.equals(result)) {
                    notHandled = false;
                }
                if (!shouldContinue(result, handler, method, args)) {
                    break;
                }
            }
        } catch (InvocationTargetException e) {
            throw e.getCause();
        }
    }
    if (notHandled) {
        return ExtensionResultStatusType.NOT_HANDLED;
    } else {
        return ExtensionResultStatusType.HANDLED;
    }
}

From source file:org.pentaho.proxy.creators.userdetailsservice.S4UserDetailsServiceProxyCreatorTest.java

@Test
public void testNoUserDetailsProxyWrapper() {

    Object wrappedObject = new S4UserDetailsServiceProxyCreatorForTest().create(mockUserDetailsService);

    Assert.assertNotNull(wrappedObject);

    Method loadUserByUsernameMethod = ReflectionUtils.findMethod(wrappedObject.getClass(), "loadUserByUsername",
            String.class);

    try {//from   w  w  w  .  jav  a  2 s. c om
        loadUserByUsernameMethod.invoke(wrappedObject, MOCK_USERNAME_NOT_EXISTS);
        Assert.fail();

    } catch (InvocationTargetException e) {
        Assert.assertTrue(e.getCause() instanceof UsernameNotFoundException);
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        Assert.fail();
    }

    try {
        loadUserByUsernameMethod.invoke(wrappedObject, MOCK_USERNAME_NOT_EXISTS_RETURNS_NULL);
        Assert.fail();

    } catch (InvocationTargetException e) {
        Assert.assertTrue(e.getCause() instanceof UsernameNotFoundException);
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
        Assert.fail();
    }
}

From source file:libepg.epg.section.descriptor.DescriptorTest.java

@Test
@ExpectedExceptionMessage("^????????.*$")
public void testConstructor_1() throws Throwable {
    try {/*from w  w  w  .ja v  a2 s. co m*/
        LOG.debug("_?");
        byte[] tail = { 0x00, 0x00 };
        byte[] wrongX1 = ArrayUtils.addAll(this.descs.getSERVICE_DESCRIPTOR_BYTE(), tail);
        Descriptor instance = Descriptors.init(wrongX1);
    } catch (InvocationTargetException ex) {
        throw ex.getCause();
    }
}

From source file:com.liferay.maven.arquillian.internal.tasks.ExecuteDeployerTask.java

protected void executeTool(String deployerClassName, ClassLoader classLoader, String[] args) throws Exception {

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    currentThread.setContextClassLoader(classLoader);

    SecurityManager currentSecurityManager = System.getSecurityManager();

    // Required to prevent premature exit by DBBuilder. See LPS-7524.
    SecurityManager securityManager = new SecurityManager() {

        @Override/*from   w  w  w  . j a va 2s.  c  o  m*/
        public void checkPermission(Permission permission) {
        }

        @Override
        public void checkExit(int status) {
            throw new SecurityException();
        }
    };

    System.setSecurityManager(securityManager);

    try {
        System.setProperty("external-properties",
                "com/liferay/portal/tools/dependencies" + "/portal-tools.properties");
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

        Class<?> clazz = classLoader.loadClass(deployerClassName);

        Method method = clazz.getMethod("main", String[].class);

        method.invoke(null, (Object) args);
    } catch (InvocationTargetException ite) {
        if (!(ite.getCause() instanceof SecurityException)) {
            throw ite;
        }
    } finally {
        currentThread.setContextClassLoader(contextClassLoader);

        System.setSecurityManager(currentSecurityManager);
    }
}

From source file:io.dropwizard.sharding.dao.WrapperDao.java

/**
 * Create a relational DAO./*from   w w  w  .ja  v  a 2s .c  o  m*/
 * @param sessionFactories List of session factories, one for each shard
 * @param daoClass Class for the dao.
 * @param shardManager The {@link ShardManager} used to manage the bucket to shard mapping.
 * @param extraConstructorParamClasses Class names for constructor parameters to the DAO other than SessionFactory
 * @param extraConstructorParamObjects Objects for constructor parameters to the DAO other than SessionFactory
 */
public WrapperDao(List<SessionFactory> sessionFactories, Class<DaoType> daoClass, ShardManager shardManager,
        BucketIdExtractor<String> bucketIdExtractor, Class[] extraConstructorParamClasses,
        Class[] extraConstructorParamObjects) {
    this.shardManager = shardManager;
    this.bucketIdExtractor = bucketIdExtractor;
    this.daos = sessionFactories.stream().map((SessionFactory sessionFactory) -> {
        Enhancer enhancer = new Enhancer();
        enhancer.setUseFactory(false);
        enhancer.setSuperclass(daoClass);
        enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
            final ShardedTransaction transaction = method.getAnnotation(ShardedTransaction.class);
            if (null == transaction) {
                return proxy.invokeSuper(obj, args);
            }
            final TransactionHandler transactionHandler = new TransactionHandler(sessionFactory,
                    transaction.readOnly());
            try {
                transactionHandler.beforeStart();
                Object result = proxy.invokeSuper(obj, args);
                transactionHandler.afterEnd();
                return result;
            } catch (InvocationTargetException e) {
                transactionHandler.onError();
                throw e.getCause();
            } catch (Exception e) {
                transactionHandler.onError();
                throw e;
            }
        });
        return createDAOProxy(sessionFactory, enhancer, extraConstructorParamClasses,
                extraConstructorParamObjects);
    }).collect(Collectors.toList());
}

From source file:au.edu.anu.metadatastores.service.search.DisplayPage.java

/**
 * Get the page/*from  w  w w.  j  av  a2  s.c  o  m*/
 * 
 * @param obj The object
 * @return The viewable
 */
public Viewable getPage(Object obj) throws Exception {
    for (Method method : DisplayPage.class.getMethods()) {
        if (method.getName().equals("getPage") && method.getParameterTypes()[0] == obj.getClass()) {
            try {
                Viewable returnObj = (Viewable) method.invoke(this, obj);
                return returnObj;
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof AccessDeniedException) {
                    throw new AccessDeniedException(e.getCause().getMessage());
                } else {
                    LOGGER.info("Error invoking method");
                    throw e;
                }
            }
        }
    }

    throw new RuntimeException("Cannot get the page for the class " + obj.getClass().getName());
}

From source file:com.google.code.guice.repository.configuration.PersistenceUnitConfiguration.java

/**
 * Represents current configuration as an EntityManager proxy. This is required for cases where
 * Configuration's EM can be changed at runtime - such as in Web-environments (see {@link PersistFilter}.
 *
 * @return proxy with EntityManager interface bound to current EM instance
 *
 * @see PersistenceUnitsConfigurationManager#changeEntityManager(String, EntityManager)
 * @see PersistFilter//from w ww . j  a  va  2  s  . c o  m
 */
public EntityManager asEntityManagerProxy() {
    return (EntityManager) Proxy.newProxyInstance(getClass().getClassLoader(),
            new Class[] { EntityManager.class }, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        return method.invoke(getEntityManager(), args);
                    } catch (InvocationTargetException e) {
                        Throwable t = e.getCause();
                        if (t != null) {
                            throw t;
                        } else {
                            throw e;
                        }
                    }
                }
            });
}

From source file:net.officefloor.plugin.web.http.template.PropertyHttpTemplateWriter.java

@Override
public void write(ServerWriter writer, boolean isDefaultCharset, Object bean, HttpApplicationLocation location)
        throws IOException {

    // If no bean, then no value to output
    if (bean == null) {
        return;//from   w  w w. ja v  a 2s.  c  o m
    }

    // Obtain the property text value
    String propertyTextValue;
    try {

        // Obtain the property value from bean
        Object value = this.valueRetriever.retrieveValue(bean, this.propertyName);

        // Obtain the text value to write as content
        propertyTextValue = (value == null ? "" : value.toString());

    } catch (InvocationTargetException ex) {
        // Propagate cause of method failure
        throw new IOException(ex.getCause());
    } catch (Exception ex) {
        // Propagate failure
        throw new IOException(ex);
    }

    // Write out the value
    if (this.isEscaped) {
        // Write the escaped value
        StringEscapeUtils.ESCAPE_HTML4.translate(propertyTextValue, writer);
    } else {
        // Write the raw value
        writer.write(propertyTextValue);
    }
}

From source file:org.pentaho.di.ui.repo.RepositorySessionTimeoutHandler.java

@SuppressWarnings("unchecked")
@Override/* ww  w . j a  v  a 2s .  c om*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        String methodName = method.getName();
        if (GET_SERVICE_METHOD_NAME.equals(methodName)) {
            return wrapRepositoryServiceWithTimeoutHandler(
                    (Class<? extends IRepositoryService>) args[SERVICE_CLASS_ARGUMENT]);
        }
        if (GET_META_STORE_METHOD_NAME.equals(methodName)) {
            return metaStoreInstance;
        }
        Object result = method.invoke(repository, args);
        if (CONNECT_METHOD_NAME.equals(methodName)) {
            IMetaStore metaStore = repository.getMetaStore();
            metaStoreInstance = wrapMetastoreWithTimeoutHandler(metaStore, sessionTimeoutHandler);
        }
        return result;
    } catch (InvocationTargetException ex) {
        if (connectedToRepository()) {
            return sessionTimeoutHandler.handle(repository, ex.getCause(), method, args);
        }
        throw ex.getCause();
    }
}

From source file:de.davidbilge.spring.remoting.amqp.service.AmqpServiceMessageListener.java

@Override
public void onMessage(Message message) {
    Address replyToAddress = message.getMessageProperties().getReplyToAddress();

    Map<String, Object> headers = message.getMessageProperties().getHeaders();
    Object invokedMethodRaw = headers.get(Constants.INVOKED_METHOD_HEADER_NAME);
    if (invokedMethodRaw == null || !(invokedMethodRaw instanceof String)) {
        send(new RuntimeException("The 'invoked method' header is missing (expected name '"
                + Constants.INVOKED_METHOD_HEADER_NAME + "')"), replyToAddress);
        return;//from   w  ww.ja  v a 2  s  .  c o  m
    }

    String invokedMethodName = (String) invokedMethodRaw;
    Method invokedMethod = methodCache.get(invokedMethodName);
    if (invokedMethod == null) {
        send(new RuntimeException(
                "The invoked method does not exist on the service (Method: '" + invokedMethodName + "')"),
                replyToAddress);
        return;
    }

    Object argumentsRaw = messageConverter.fromMessage(message);
    Object[] arguments;
    if (argumentsRaw instanceof Object[]) {
        arguments = (Object[]) argumentsRaw;
    } else {
        send(new RuntimeException("The message does not contain an argument array"), replyToAddress);
        return;
    }

    Object retVal;
    try {
        retVal = invokedMethod.invoke(getService(), arguments);
    } catch (InvocationTargetException ite) {
        send(ite.getCause(), replyToAddress);
        return;
    } catch (Throwable e) {
        send(e, replyToAddress);
        return;
    }

    send(retVal, replyToAddress);
}