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:hudson.plugins.active_directory.ActiveDirectoryUserDetail.java

/**
 * Gets the corresponding {@link hudson.model.User} object.
 *//*from  w w  w . j  a  v a 2s  .c  o  m*/
public hudson.model.User getJenkinsUser() {
    try { // TODO 1.651.2+ remove reflection
        return (hudson.model.User) hudson.model.User.class.getMethod("getById", String.class, boolean.class)
                .invoke(null, getUsername(), true);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof RuntimeException) {
            throw (RuntimeException) e.getCause();
        }
        // Only RuntimeException is expected
        LOGGER.log(Level.WARNING,
                String.format("There was a problem obtaining the Jenkins user %s by Id", getUsername()), e);
    } catch (NoSuchMethodException e) {
        // fine, older baseline
    } catch (Exception e) { // unexpected
        LOGGER.log(Level.WARNING,
                String.format("There was a problem obtaining the Jenkins user %s by Id", getUsername()), e);
    }
    return hudson.model.User.get(getUsername());
}

From source file:net.netheos.pcsapi.storage.StorageBuilder.java

/**
 * Builds a provider-specific storage implementation, by passing this builder in constructor. Each implementation
 * gets its required information from builder.
 *
 * @return The storage builder//from   w  ww. ja  v  a  2  s .  com
 */
public IStorageProvider build() {
    if (appInfoRepo == null) {
        throw new IllegalStateException("Undefined application information repository");
    }
    if (userCredentialsRepo == null) {
        throw new IllegalStateException("Undefined user credentials repository");
    }

    try {
        Constructor providerConstructor = providerClass.getConstructor(StorageBuilder.class);
        StorageProvider providerInstance = (StorageProvider) providerConstructor.newInstance(this);
        return providerInstance;

    } catch (InvocationTargetException itex) {
        Throwable cause = itex.getCause();
        if (cause instanceof RuntimeException) {
            throw (RuntimeException) cause;
        }
        // should not happen, providers constructors do not throw checked exceptions:
        throw new UnsupportedOperationException(
                "Error instantiating the provider " + providerClass.getSimpleName(), itex);
    } catch (Exception ex) {
        throw new UnsupportedOperationException(
                "Error instantiating the provider " + providerClass.getSimpleName(), ex);
    }
}

From source file:com.palantir.leader.proxy.AwaitingLeadershipProxy.java

@Override
protected Object handleInvocation(Object proxy, Method method, Object[] args) throws Throwable {
    final LeadershipToken leadershipToken = leadershipTokenRef.get();

    if (leadershipToken == null) {
        throw notCurrentLeaderException("method invoked on a non-leader");
    }//ww  w  .java 2s.c om

    if (method.getName().equals("close") && args.length == 0) {
        isClosed = true;
        executor.shutdownNow();
        clearDelegate();
        return null;
    }

    Object delegate = delegateRef.get();
    StillLeadingStatus leading;
    do {
        leading = leaderElectionService.isStillLeading(leadershipToken);
    } while (leading == StillLeadingStatus.NO_QUORUM);

    if (leading == StillLeadingStatus.NOT_LEADING) {
        markAsNotLeading(leadershipToken, null /* cause */);
    }

    if (isClosed) {
        throw new IllegalStateException("already closed proxy for " + interfaceClass.getName());
    }

    Preconditions.checkNotNull(delegate, interfaceClass.getName() + " backing is null");
    try {
        return method.invoke(delegate, args);
    } catch (InvocationTargetException e) {
        if (e.getCause() instanceof ServiceNotAvailableException
                || e.getCause() instanceof NotCurrentLeaderException) {
            markAsNotLeading(leadershipToken, e.getCause());
        }
        throw e.getCause();
    }
}

From source file:blue.lapis.pore.impl.event.PoreEventImplTest.java

@Test
public void checkConstructor() throws Throwable {
    for (Constructor<?> constructor : eventImpl.getConstructors()) {
        Class<?>[] parameters = constructor.getParameterTypes();
        if (parameters.length == 1) {
            Class<?> handle = parameters[0];
            if (org.spongepowered.api.event.Event.class.isAssignableFrom(handle)) {
                // Check for null check
                try {
                    constructor.newInstance(new Object[] { null });
                } catch (InvocationTargetException e) {
                    Throwable cause = e.getCause();
                    if (cause != null) {
                        if (cause instanceof NullPointerException
                                && Objects.equal(cause.getMessage(), "handle")) {
                            return;
                        }/*w w  w.  ja va 2 s . c  o  m*/

                        throw cause;
                    }

                    throw e;
                }

                fail(eventImpl.getSimpleName() + ": missing null-check for handle");
            }
        }
    }

    fail(eventImpl.getSimpleName() + ": missing handle constructor");
}

From source file:edu.mayo.cts2.framework.webapp.service.AbstractServiceAwareBean.java

/**
 * Load services./*from ww  w .  j a v  a2 s  .c o m*/
 */
protected void loadServices() {

    for (Field field : this.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(Cts2Service.class)) {

            @SuppressWarnings("unchecked")
            final Class<? extends Cts2Profile> clazz = (Class<? extends Cts2Profile>) field.getType();
            ProxyFactory factory = new ProxyFactory();
            Cts2Profile service = (Cts2Profile) factory.createInvokerProxy(new Invoker() {

                @Override
                public Object invoke(Object o, Method method, Object[] arguments) throws Throwable {
                    ServiceProvider retrievedServiceProvider = serviceProviderFactory.getServiceProvider();

                    Cts2Profile retrievedService;
                    if (retrievedServiceProvider == null) {
                        throw new UnsupportedOperationException("This service is not implemented.");
                    } else {
                        retrievedService = retrievedServiceProvider.getService(clazz);

                        if (retrievedService == null) {
                            throw new UnsupportedOperationException("This service is not implemented.");
                        }
                    }

                    try {
                        return method.invoke(retrievedService, arguments);
                    } catch (InvocationTargetException e) {
                        throw e.getCause();
                    }

                }

            }, new Class<?>[] { clazz });

            if (service == null) {
                service = proxyNullService(clazz);
            }

            field.setAccessible(true);

            try {
                field.set(this, service);
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }

            log.info("Setting service: " + field.getType() + " on: " + this.getClass().getName());
        }
    }
}

From source file:com.useekm.indexing.internal.BigdataEvaluationStrategy.java

@SuppressWarnings("unchecked")
private CloseableIteration<BindingSet, QueryEvaluationException> evaluateNativeStreaming(TupleExpr expr,
        JoinWithSingletonIteration bindingSets) throws QueryEvaluationException {
    try {/*from   w w  w .ja  v a 2 s  . co  m*/
        //See remarks for streamingEvaluate member for why we have and should get rid of this reflection thing... 
        return (CloseableIteration<BindingSet, QueryEvaluationException>) streamingEvaluate.invoke(getConn(),
                expr, dataset, new QueryBindingSet(), bindingSets, isIncludeInferred(), null);
    } catch (InvocationTargetException e) {
        QueryEvaluationException newE;
        if (e.getCause() instanceof QueryEvaluationException)
            throw (QueryEvaluationException) e.getCause();
        else {
            //By writing it like this checkstyle doesn't warn about missing reference to original exception....
            newE = new QueryEvaluationException(e.getCause());
            throw newE;
        }
    } catch (IllegalArgumentException e) {
        throw new QueryEvaluationException("BigdataEvaluationStrategy is not properly initialized", e);
    } catch (IllegalAccessException e) {
        throw new QueryEvaluationException("BigdataEvaluationStrategy is not properly initialized", e);
    }
}

From source file:net.sourceforge.vulcan.EasyMockTestCase.java

private boolean train(TestCase instance) throws Throwable {
    final Class<? extends TestCase> c = instance.getClass();
    final Method testMethod = c.getMethod(instance.getName(), (Class[]) null);

    final TrainingMethod trainingMethodAnn = testMethod.getAnnotation(TrainingMethod.class);

    if (trainingMethodAnn != null) {
        final String trainingMethodNames[] = trainingMethodAnn.value().split(",");

        try {/*from  w  ww . ja v a 2s  .  c o  m*/
            for (String trainingMethodName : trainingMethodNames) {
                final Method trainingMethod = c.getMethod(trainingMethodName.trim(), (Class[]) null);
                trainingMethod.invoke(instance, (Object[]) null);
            }
            return true;
        } catch (InvocationTargetException e) {
            throw e.getCause();
        } catch (NoSuchMethodException e) {
            fail("TrainingMethod " + trainingMethodAnn.value() + " does not exist or is not accessible.");
        }
    }

    return false;
}

From source file:org.apache.axis2.rpc.receivers.RPCInOutAsyncMessageReceiver.java

/**
 * reflect and get the Java method - for each i'th param in the java method - get the first
 * child's i'th child -if the elem has an xsi:type attr then find the deserializer for it - if
 * not found, lookup deser for th i'th param (java type) - error if not found - deserialize &
 * save in an object array - end for//w w w  .j a  v  a 2s. co m
 * <p/>
 * - invoke method and get the return value
 * <p/>
 * - look up serializer for return value based on the value and type
 * <p/>
 * - create response msg and add return value as grand child of <soap:body>
 *
 * @param inMessage
 * @param outMessage
 * @throws AxisFault
 */

public void invokeBusinessLogic(MessageContext inMessage, MessageContext outMessage) throws AxisFault {
    Method method = null;
    try {
        // get the implementation class for the Web Service
        Object obj = getTheImplementationObject(inMessage);

        Class ImplClass = obj.getClass();

        AxisOperation op = inMessage.getOperationContext().getAxisOperation();
        AxisService service = inMessage.getAxisService();
        OMElement methodElement = inMessage.getEnvelope().getBody().getFirstElement();

        AxisMessage inaxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
        String messageNameSpace = null;
        String methodName = op.getName().getLocalPart();
        Method[] methods = ImplClass.getMethods();
        for (int i = 0; i < methods.length; i++) {
            if (methods[i].isBridge()) {
                continue;
            }
            if (methods[i].getName().equals(methodName)) {
                method = methods[i];
                break;
            }
        }
        Object resObject = null;
        if (inaxisMessage != null) {
            resObject = RPCUtil.invokeServiceClass(inaxisMessage, method, obj, messageNameSpace, methodElement,
                    inMessage);
        }

        SOAPFactory fac = getSOAPFactory(inMessage);

        // Handling the response

        AxisMessage outaxisMessage = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
        if (outaxisMessage != null && outaxisMessage.getElementQName() != null) {
            messageNameSpace = outaxisMessage.getElementQName().getNamespaceURI();
        } else {
            messageNameSpace = service.getTargetNamespace();
        }

        OMNamespace ns = fac.createOMNamespace(messageNameSpace, service.getSchemaTargetNamespacePrefix());
        SOAPEnvelope envelope = fac.getDefaultEnvelope();
        OMElement bodyContent = null;

        if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals(op.getMessageExchangePattern())) {
            OMElement bodyChild = fac.createOMElement(outMessage.getAxisMessage().getName(), ns);
            envelope.getBody().addChild(bodyChild);
            outMessage.setEnvelope(envelope);
            return;
        }
        Parameter generateBare = service.getParameter(Java2WSDLConstants.DOC_LIT_BARE_PARAMETER);
        if (generateBare != null && "true".equals(generateBare.getValue())) {
            RPCUtil.processResonseAsDocLitBare(resObject, service, envelope, fac, ns, bodyContent, outMessage);
        } else {
            RPCUtil.processResponseAsDocLitWrapped(resObject, service, method, envelope, fac, ns, bodyContent,
                    outMessage);
        }
        outMessage.setEnvelope(envelope);
    } catch (InvocationTargetException e) {
        String msg = null;
        Throwable cause = e.getCause();
        if (cause != null) {
            msg = cause.getMessage();
        }
        if (msg == null) {
            msg = "Exception occurred while trying to invoke service method " + method.getName();
        }
        log.error(msg, e);
        if (cause instanceof AxisFault) {
            throw (AxisFault) cause;
        }
        throw new AxisFault(msg);
    } catch (Exception e) {
        String msg = "Exception occurred while trying to invoke service method " + method.getName();
        log.error(msg, e);
        throw new AxisFault(msg, e);
    }
}

From source file:com.anrisoftware.globalpom.reflection.beans.BeanAccessImplLogger.java

ReflectionError invocationTargetError(InvocationTargetException e, Object bean, String fieldName,
        Method getter) {//from www  .  ja  v  a  2  s  .c o  m
    return logException(new ReflectionError(exception_thrown, e.getCause()).add(bean, bean)
            .add(field, fieldName).add(getter, getter), exception_getter_message, getter, bean, fieldName);
}

From source file:org.springframework.cloud.sleuth.instrument.async.ExecutorBeanPostProcessor.java

@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Executor executor = executor(this.beanFactory, this.delegate);
    Method methodOnTracedBean = getMethod(invocation, executor);
    if (methodOnTracedBean != null) {
        try {//from   www  . j  av  a2 s.  co m
            return methodOnTracedBean.invoke(executor, invocation.getArguments());
        } catch (InvocationTargetException ex) {
            // gh-1092: throw the target exception (if present)
            Throwable cause = ex.getCause();
            throw (cause != null) ? cause : ex;
        }
    }
    return invocation.proceed();
}