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.plasma.sdo.DataConverterTest.java

/**
 * Checks the given data type as a source for conversion to all other SDO specified datatypes, expecting
 * conversion errors thrown from the DataConverter based on the DataConverter.getAllowableTargetTypes()
 * method. //from ww  w . ja  v  a  2 s . c om
 * @param testDataType
 * @throws Throwable
 */
private void checkAsSource(DataType testDataType) throws Throwable {
    DataType[] allTypes = DataType.values();
    for (int i = 0; i < allTypes.length; i++) {
        DataType currentDataType = allTypes[i];
        Type currentType = TypeHelper.INSTANCE.getType(
                PlasmaConfig.getInstance().getSDODataTypesNamespace().getUri(), currentDataType.name());

        // check the current type as a source type
        List<DataType> allowedToTestDataType = DataConverter.INSTANCE.getAllowableTargetTypes(currentDataType);
        Class[] toArgsTypes = { Type.class, Object.class };
        String toMethodName = "to" + testDataType.name();
        Method toMethod = DataConverter.INSTANCE.getClass().getMethod(toMethodName, toArgsTypes);
        Object[] toArgs = { currentType, testValues[currentDataType.ordinal()][0] };
        if (findDataType(testDataType, allowedToTestDataType)) {
            try {
                Object result = toMethod.invoke(DataConverter.INSTANCE, toArgs);
                log.info("(" + testDataType.name() + ") converted from " + currentDataType.toString() + " to "
                        + testDataType.toString() + " (" + String.valueOf(result) + ")");
            } catch (InvocationTargetException e) {
                throw e.getTargetException();
            }
        } else {
            try {
                toMethod.invoke(DataConverter.INSTANCE, toArgs);
                assertTrue("expected error on conversion " + currentType.getName() + "->" + testDataType.name(),
                        false);
            } catch (InvocationTargetException e) {
                assertTrue("expected class-cast-exception",
                        e.getTargetException() instanceof ClassCastException);
                log.debug("(" + testDataType.name() + ") prevented conversion from "
                        + currentDataType.toString() + " to " + testDataType.toString() + " ");
            }
        }
    }
}

From source file:org.polymap.core.operation.OperationExecutor.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (method.getName().equals("equals")) {
        return proxy == args[0];
    } else if (method.getName().equals("hashCode")) {
        return hashCode();
    } else {//w  ww.  j a v  a  2  s .  c o m
        try {
            //                if (lock.isHeldByCurrentThread()) {
            //                    throw new IllegalStateException( "Reentrant calls from operation and/or concerns into same operation are not allowed." );
            //                }

            concernIndex.set(new AtomicInteger(0));
            return method.invoke(next(), args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        } finally {
            concernIndex.set(null);
        }
    }
}

From source file:org.polymap.core.runtime.event.DisplayingListener.java

@Override
public void handleEvent(final EventObject ev) throws Exception {
    if (display.isDisposed()) {
        log.warn("Display is disposed!");
        delegate = null;//from w w w.j a v  a  2  s.  c  o  m
    } else {
        display.asyncExec(new Runnable() {
            public void run() {
                try {
                    delegate.handleEvent(ev);
                }
                // as this is used by AnnotatedEventListener
                catch (InvocationTargetException e) {
                    log.warn("Error during event dispatch: " + e.getTargetException(), e.getTargetException());
                } catch (Exception e) {
                    log.warn("Error during event dispatch: " + e, e);
                }
            }
        });
    }
}

From source file:org.rhq.core.system.SigarAccessHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // its possible in the time between this handler's creation and now, someone disabled the native layer.
    // throw a runtime exception if the native system was disabled
    if (SystemInfoFactory.isNativeSystemInfoDisabled()) {
        throw new SystemInfoException("Native system has been disabled");
    }//from ww  w.ja  v a2  s.c  o  m

    // Acquire lock for shared Sigar instance. Wait 'sharedSigarLockMaxWait' seconds at most
    boolean acquiredLock = sharedSigarLock.tryLock(SHARED_SIGAR_LOCK_MAX_WAIT, SECONDS);
    if (acquiredLock) {
        try {
            if (closed) {
                throw new SystemInfoException("SigarAccess has been closed");
            }
            if (sharedSigar == null) {
                this.sharedSigar = sigarFactory.createSigarInstance();
            }
            return method.invoke(sharedSigar, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        } finally {
            sharedSigarLock.unlock();
        }
    } else {
        Sigar localSigar = createLocalSigarInstance();
        try {
            return method.invoke(localSigar, args);
        } catch (InvocationTargetException e) {
            throw e.getTargetException();
        } finally {
            closeLocalSigarInstance(localSigar);
        }
    }
}

From source file:org.rhq.enterprise.server.remote.RemoteSafeInvocationHandler.java

public Object invoke(InvocationRequest invocationRequest) throws Throwable {

    if (invocationRequest == null) {
        throw new IllegalArgumentException("InvocationRequest was null.");
    }//from ww  w .  jav  a2 s. co m

    String methodName = null;
    boolean successful = false; // we will flip this to true when we know we were successful
    Object result = null;
    long time = System.currentTimeMillis();

    try {
        InitialContext ic = new InitialContext();

        NameBasedInvocation nbi = ((NameBasedInvocation) invocationRequest.getParameter());
        if (null == nbi) {
            throw new IllegalArgumentException("InvocationRequest did not supply method.");
        }

        methodName = nbi.getMethodName();
        String[] methodInfo = methodName.split(":");

        // Lookup the remote first, if it doesn't exist exit with error.
        // This prevents remote clients from accessing the locals.
        String jndiName = "rhq/" + methodInfo[0];
        Object target = ic.lookup(jndiName + "/remote");
        target = ic.lookup(jndiName + "/local");

        String[] signature = nbi.getSignature();
        int signatureLength = signature.length;
        Class<?>[] sig = new Class[signatureLength];
        for (int i = 0; i < signatureLength; i++) {
            sig[i] = getClass(signature[i]);
        }

        Method m = target.getClass().getMethod(methodInfo[1], sig);
        result = m.invoke(target, nbi.getParameters());
        successful = true;
    } catch (InvocationTargetException e) {
        log.error("Failed to invoke remote request", e);
        return new WrappedRemotingException(e.getTargetException());
    } catch (Exception e) {
        log.error("Failed to invoke remote request", e);
        return new WrappedRemotingException(e);
    } finally {
        if (result != null) {
            // set the strategy guiding how the return information is serialized
            ExternalizableStrategy.setStrategy(ExternalizableStrategy.Subsystem.REFLECTIVE_SERIALIZATION);

            // scrub the return data if Hibernate proxies
            try {
                HibernateDetachUtility.nullOutUninitializedFields(result,
                        HibernateDetachUtility.SerializationType.SERIALIZATION);
            } catch (Exception e) {
                log.error("Failed to null out uninitialized fields", e);
                this.metrics.addData(methodName, System.currentTimeMillis() - time, false);

                return new WrappedRemotingException(e);
            }
        }

        // want to calculate this after the hibernate util so we take that into account too
        long executionTime = System.currentTimeMillis() - time;
        this.metrics.addData(methodName, executionTime, successful);
        if (log.isDebugEnabled()) {
            log.debug("Remote request [" + methodName + "] execution time (ms): " + executionTime);
        }
    }

    return result;
}

From source file:org.rhq.plugins.www.snmp.SNMPSessionCache.java

public Object invoke(Object proxy, Method method, Object[] args) throws SNMPException {
    SNMPCacheObject cacheVal = null;/*w ww. ja  v a  2  s .c o m*/
    Map cache = null;

    Object cacheKey = null;
    Object retval;
    String name = method.getName();

    long timeNow = 0;

    //XXX perhaps more later
    if (name.equals("getBulk")) {
        cache = this.bulkCache;
        cacheKey = args[0];
    } else if (name.equals("getTable")) {
        cache = this.tableCache;
        cacheKey = args[0].hashCode() ^ args[1].hashCode();
    } else if (name.equals("getColumn")) {
        cache = this.columnCache;
        cacheKey = args[0];
    }

    if (cache != null) {
        timeNow = System.currentTimeMillis();
        cacheVal = getFromCache(timeNow, cache, name, cacheKey);

        if (cacheVal.value != null) {
            return cacheVal.value;
        }
    }

    try {
        retval = method.invoke(this.session, args);
    } catch (InvocationTargetException e) {
        SNMPException snmpException;
        Throwable t = e.getTargetException();
        if (t instanceof SNMPException) {
            snmpException = (SNMPException) t;
        } else {
            String msg = t + " (while invoking: " + invokerToString(name, args, cacheKey) + ")";
            snmpException = new SNMPException(msg);
        }

        throw snmpException;
    } catch (Exception e) {
        String msg = e + " (while invoking: " + invokerToString(name, args, cacheKey) + ")";
        throw new SNMPException(msg);
    }

    if (cacheVal != null) {
        cacheVal.value = retval;
        cacheVal.timestamp = timeNow;

        //if (log.isDebugEnabled()) {
        //    log.debug(invokerToString(name, args, cacheKey) +
        //              " took: " + new net.hyperic.util.timer.StopWatch(timeNow));
        //}
    }

    return retval;
}

From source file:org.romaframework.core.flow.Controller.java

public void executeAction(Object iContent, SchemaAction iAction) throws Throwable {
    if (iContent == null || iAction == null) {
        return;/*from  w ww .  j  ava  2 s  . c  om*/
    }

    if (log.isDebugEnabled()) {
        log.debug("[Controller.executeAction] Executing action: " + iAction + " on object "
                + iContent.toString() + "...");
    }

    try {
        iAction.invoke(iContent);
    } catch (InvocationTargetException ex) {
        Throwable nestedExc = ex.getTargetException();
        if (nestedExc == null
                || !(nestedExc instanceof UserException) && !(nestedExc instanceof MultiValidationException)) {

            String errorLabel = I18NAspect.VARNAME_PREFIX + iAction.getName() + ERROR_LABEL;

            log.warn("[Controller.executeAction] error on execution of method: " + iAction.getName(),
                    nestedExc);

            // WRAP THE EXCEPTION IN A NEW USER EXCEPTION TAKING THE ACTION
            // NAME
            throw new UserException(iContent, errorLabel, nestedExc);
        }
        // THROW THE NESTED EXCEPTION (BYPASS THE REFLECTION)
        throw nestedExc;
    }
}

From source file:org.sapia.soto.state.util.FormStep.java

private void assign(Object bean, Result res) {
    Param p;//  w  w  w.j  a v a  2s  .c o m

    for (int i = 0; i < _params.size(); i++) {
        p = (Param) _params.get(i);

        try {
            if (p._encoding == null && _encoding != null) {
                p._encoding = _encoding;
            }
            p.process(bean, res.getContext());
        } catch (InvocationTargetException e) {
            res.error(e.getTargetException());

            return;
        } catch (IllegalAccessException e) {
            res.error(e);

            return;
        } catch (NoSuchMethodException e) {
            res.error(e);

            return;
        }
    }
}

From source file:org.sigmah.server.servlet.base.AbstractServlet.java

/**
 * Secures the given {@code servletMethod} execution.
 * /*from   w  w w  .j a v  a  2  s .c  om*/
 * @param request
 *          The HTTP request.
 * @param response
 *          The HTTP response.
 * @param servletMethod
 *          Java servlet method to execute once user session has been secured.
 * @throws ServletException
 *           If the servlet execution fails.
 */
private void secureServlet(final HttpServletRequest request, final HttpServletResponse response,
        final Method servletMethod) throws ServletException {

    if (servletMethod == null) {
        if (LOG.isErrorEnabled()) {
            LOG.error("The given servlet method {} is null.", servletMethod);
        }
        throw new IllegalArgumentException("Servlet method is required.");
    }

    User user = null;

    try {

        // Validates the user session and user access.
        final String authenticationToken = request.getParameter(ServletConstants.AUTHENTICATION_TOKEN);
        final String originPageToken = request.getParameter(ServletConstants.ORIGIN_PAGE_TOKEN);

        final String servletPath = request.getRequestURI().replaceFirst(ServletModule.ENDPOINT, "");
        final Servlet servletEnum = Servlet.fromPathName(servletPath);
        final ServletMethod servletMethodEnum = ServletMethod.fromMethodName(servletMethod.getName());

        final Access access = secureSessionValidator.validate(authenticationToken, servletEnum,
                servletMethodEnum, originPageToken);
        user = access.getUser();

        switch (access.getAccessType()) {

        case INVALID_SESSION:

            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "SERVLET METHOD EXECUTION FAILED - Servlet method: '{}' ; User: '{}' ; Error: Invalid auth token '{}'.",
                        servletMethod, Servlets.logUser(user), authenticationToken);
            }

            throw new InvalidSessionException("Your session is no longer valid.");

        case UNAUTHORIZED_ACCESS:

            if (LOG.isDebugEnabled()) {
                LOG.debug(
                        "SERVLET METHOD EXECUTION FAILED - Servlet method: '{}' ; User: '{}' ; Error: Unauthorized process.",
                        servletMethod, Servlets.logUser(user));
            }

            throw new UnauthorizedAccessException("You are not authorized to execute this process.");

        default:

            // Access granted, executes servlet method.
            if (LOG.isDebugEnabled()) {
                LOG.debug("SERVLET METHOD EXECUTION GRANTED - Servlet method: '{}' ; User: '{}'.",
                        servletMethod, Servlets.logUser(user));
            }

            // Activate filters into hibernate session.
            DomainFilters.applyUserFilter(user, entityManagerProvider.get());

            final StopWatch chrono = new StopWatch();
            chrono.start();

            servletMethod.setAccessible(true);
            servletMethod.invoke(this, request, response,
                    new ServletExecutionContext(access.getUser(), request, originPageToken));

            if (LOG.isDebugEnabled()) {
                LOG.debug("SERVLET METHOD '{}' EXECUTED IN {} MS.", servletMethod, chrono.getTime());
            }
        }

    } catch (final InvocationTargetException e) {

        // NO NEED TO LOG EXCEPTION HERE.

        if (e.getTargetException() instanceof ServletException) {
            // Servlet exception.
            throw (ServletException) e.getTargetException();

        } else if (e.getTargetException() instanceof ConstraintViolationException) {
            // Bean validation failed.
            final ConstraintViolationException cve = (ConstraintViolationException) e.getTargetException();

            if (LOG.isErrorEnabled()) {
                LOG.error("SERVLET METHOD EXECUTION FAILED - Servlet method: '" + servletMethod + "' ; User: '"
                        + Servlets.logUser(user)
                        + "' ; Error: A bean validation failed during servlet method execution. Consider performing the validation on client-side.\n"
                        + Servlets.logConstraints(cve.getConstraintViolations()));
            }

            throw new ServletException(e.getCause().getMessage(), cve);

        } else {
            throw new ServletException(e.getCause().getMessage(), e.getTargetException());
        }

    } catch (final Throwable e) {
        // Server unknown error.
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.sonar.ide.eclipse.ui.internal.wizards.associate.ConfigureProjectsPage.java

private void scheduleAutomaticAssociation() {
    getShell().addShellListener(new ShellAdapter() {
        @Override/*  w  ww .  ja  v  a  2  s  .  c om*/
        public void shellActivated(ShellEvent shellevent) {
            if (!alreadyRun) {
                alreadyRun = true;
                try {
                    if (sonarServers.isEmpty()) {
                        setMessage("Please configure a SonarQube server first", IMessageProvider.ERROR);
                    } else {
                        setMessage("", IMessageProvider.NONE);
                        getWizard().getContainer().run(true, false,
                                new AssociateProjects(sonarServers, getProjects()));
                    }
                } catch (InvocationTargetException ex) {
                    LOG.error(ex.getMessage(), ex);
                    if (ex.getTargetException() instanceof ConnectionException) {
                        setMessage(
                                "One of your SonarQube server cannot be reached. Please check your connection settings.",
                                IMessageProvider.ERROR);
                    } else {
                        setMessage("Error: " + ex.getMessage(), IMessageProvider.ERROR);
                    }
                } catch (Exception ex) {
                    LOG.error(ex.getMessage(), ex);
                    setMessage("Error: " + ex.getMessage(), IMessageProvider.ERROR);
                }
            }
        }
    });
}