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.nuxeo.runtime.remoting.transporter.TransporterClient.java

/**
 * The method called when anyone calls on the dynamic proxy returned by
 * getProcessor(). This method will simply convert the proxy call info into
 * a remoting invocation on the target remoting server (using a
 * NameBaseInvocation).//from www .  j a  va2s .c om
 */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    String methodName = method.getName();
    String[] paramSig = createParamSignature(method.getParameterTypes());

    NameBasedInvocation request = new NameBasedInvocation(methodName, args, paramSig);
    Object response = null;

    boolean failOver = false;

    do {
        try {
            failOver = false;
            response = remotingClient.invoke(request);
        } catch (CannotConnectException cnc) {
            //failOver = findAlternativeTarget();
            if (!failOver) {
                throw cnc;
            }
        } catch (InvocationTargetException itex) {
            throw itex.getCause();
        }
    } while (failOver);

    return response;
}

From source file:fr.xebia.management.ServletContextAwareMBeanServerFactory.java

public MBeanServer getObject() throws Exception {
    if (instance == null) {
        InvocationHandler invocationHandler = new InvocationHandler() {
            /**/*from  ww  w. j a v  a  2  s .co  m*/
             * <p>
             * Copy the given <code>objectName</code> adding the extra
             * attributes.
             * </p>
             */
            protected ObjectName addExtraAttributesToObjectName(ObjectName objectName)
                    throws MalformedObjectNameException {
                Hashtable<String, String> table = new Hashtable<String, String>(
                        objectName.getKeyPropertyList());
                table.putAll(objectNameExtraAttributes);

                ObjectName result = ObjectName.getInstance(objectName.getDomain(), table);
                logger.trace("addExtraAttributesToObjectName({}): {}", objectName, result);

                return result;
            }

            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object[] modifiedArgs = args.clone();
                for (int i = 0; i < modifiedArgs.length; i++) {
                    Object arg = modifiedArgs[i];
                    if (arg instanceof ObjectName) {
                        ObjectName objectName = (ObjectName) arg;
                        modifiedArgs[i] = addExtraAttributesToObjectName(objectName);
                    }
                }
                if (logger.isDebugEnabled()) {
                    logger.debug(method + " : " + Arrays.asList(modifiedArgs));
                }
                try {
                    return method.invoke(server, modifiedArgs);
                } catch (InvocationTargetException ite) {
                    throw ite.getCause();
                }
            }
        };
        instance = (MBeanServer) Proxy.newProxyInstance(ClassUtils.getDefaultClassLoader(),
                new Class[] { MBeanServer.class }, invocationHandler);

    }
    return instance;
}

From source file:org.jlibrary.servlet.service.HTTPStreamingServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (logger.isDebugEnabled()) {
        logger.debug("Received a POST request");
    }//from  ww  w.ja va 2  s  . c  o  m

    try {
        InputStream stream = req.getInputStream();
        byte[] count = read(stream, 4);
        int messageNameSize = ByteUtils.byteArrayToInt(count);

        byte[] messageNameBuffer = read(stream, messageNameSize);
        String callMethodName = new String(messageNameBuffer);

        Object returnValue = null;
        boolean streamOutput = false;
        boolean streamInput = false;

        if (callMethodName.equals("stream-input")) {
            // Streaming request. Re-read call method name
            streamInput = true;

            count = read(stream, 4);
            messageNameSize = ByteUtils.byteArrayToInt(count);
            messageNameBuffer = read(stream, messageNameSize);
            callMethodName = new String(messageNameBuffer);
        } else if (callMethodName.equals("stream-output")) {
            // Streaming request. Re-read call method name
            streamOutput = true;

            count = read(stream, 4);
            messageNameSize = ByteUtils.byteArrayToInt(count);
            messageNameBuffer = read(stream, messageNameSize);
            callMethodName = new String(messageNameBuffer);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Calling method: " + callMethodName);
        }

        // Handle request
        count = read(stream, 4);
        int parameters = ByteUtils.byteArrayToInt(count);
        Object[] params = new Object[parameters];
        if (!streamInput && !streamOutput) {
            params = new Object[parameters];
        } else {
            params = new Object[parameters + 1];
            if (streamInput) {
                params[parameters] = stream;
            } else if (streamOutput) {
                params[parameters] = resp.getOutputStream();
            }
        }
        for (int i = 0; i < parameters; i++) {
            count = read(stream, 4);
            int parameterSize = ByteUtils.byteArrayToInt(count);
            byte[] parameterBuffer = read(stream, parameterSize);
            params[i] = SerializationUtils.deserialize(parameterBuffer);
        }

        try {
            if (!streamInput && !streamOutput) {
                returnValue = handleRequest(req, callMethodName, params);
            } else if (streamInput) {
                returnValue = handleRequest(req, callMethodName, params, InputStream.class);
            } else if (streamOutput) {
                returnValue = handleRequest(req, callMethodName, params, OutputStream.class);
            }
        } catch (InvocationTargetException ite) {
            returnValue = ite.getCause();
            if (returnValue == null) {
                returnValue = ite.getTargetException();
            }
        } catch (Exception e) {
            returnValue = e;
        }

        if (!streamOutput) {
            handleReturnValue(resp, returnValue);
        }
    } catch (IOException e) {
        logger.error("IOException in doPost", e);
    } catch (Exception e) {
        logger.error("Exception in doPost", e);
    } finally {
        if (logger.isDebugEnabled()) {
            logger.debug("POST request handled successfully");
        }
    }
}

From source file:rb.app.QNTransientSCMSystem.java

/**
 * Evaluate theta_c (for the quadratic nonlinearity) at the current parameter.
 *//*w  w  w.ja  v a2  s. c  o m*/
public double eval_theta_c() {

    Method meth;

    try {
        Class partypes[] = new Class[1];
        partypes[0] = double[].class;

        meth = mAffineFnsClass.getMethod("evaluateC", partypes);
    } catch (NoSuchMethodException nsme) {
        throw new RuntimeException("getMethod for evaluateC failed", nsme);
    }

    Double theta_val;
    try {
        Object arglist[] = new Object[1];
        arglist[0] = current_parameters.getArray();

        Object theta_obj = meth.invoke(mTheta, arglist);
        theta_val = (Double) theta_obj;
    } catch (IllegalAccessException iae) {
        throw new RuntimeException(iae);
    } catch (InvocationTargetException ite) {
        throw new RuntimeException(ite.getCause());
    }

    return SCM_theta_c_scaling * theta_val.doubleValue();
}

From source file:org.mc4j.ems.impl.jmx.connection.support.providers.proxy.GenericMBeanServerProxy.java

public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {

    //        SwingUtility.eventThreadAlert();
    ////from   w w  w  .jav  a  2 s.c  o m
    //        ConnectionInfoAction.addHit();

    Class serverClass = this.remoteServer.getClass();
    //org.openide.windows.IOProvider.getDefault().getStdOut().println("Looking at object: " + serverClass.getName());

    Method method = findMethod(m, serverClass);

    //        ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
    try {
        roundTrips++;
        //            Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
        @SuppressWarnings({ "UnnecessaryLocalVariable" })
        Object returnValue = invokeInternal(args, method);
        return returnValue;
    } catch (InvocationTargetException e) {
        failures++;
        if (e.getCause() != null) {
            Throwable t = e.getCause();
            if (t instanceof java.rmi.ConnectException) {
                throw new EmsConnectException(t);
            } else if (t instanceof NoSuchObjectException) {
                // This happens when the server comes back up and the stub is stale.
                // Try to reconnect if this provider supports it (if it told the proxy what the provider was)
                if (provider != null && !reconnecting) {
                    try {
                        log.info("Reestablishing RMI stub to restarted server ["
                                + this.provider.getConnectionSettings().getServerUrl() + "]...");
                        reconnecting = true;
                        provider.connect();
                        // Retry the invocation.
                        @SuppressWarnings({ "UnnecessaryLocalVariable" })
                        Object returnValue = invokeInternal(args, method);
                        return returnValue;
                    } catch (Exception f) {
                        log.warn("Unable to reestablish RMI stub to restarted server ["
                                + this.provider.getConnectionSettings().getServerUrl() + "].", f);
                    } finally {
                        reconnecting = false;
                    }
                }
                // The reconnect failed, throw the original exception
                // If the retry fails, it will throw its own exception
                throw new EmsConnectException(t);
            } else if (t instanceof java.io.IOException) {
                throw new EmsConnectException(t);
            } else if (t instanceof NotSerializableException) {
                throw new EmsUnsupportedTypeException("Value was not serializable " + t.getLocalizedMessage(),
                        t);
            } else {
                throw new EmsConnectException("Connection failure " + t.getLocalizedMessage(), t);
            }
        } else {
            throw e;
        }
    } catch (Exception e) {
        failures++;
        // Log the method.toString() to aid debugging.
        log.error("Failed to invoke method [" + method + "]: " + e);
        //e.printStackTrace();
        throw e;
    } finally {
        //            Thread.currentThread().setContextClassLoader(ctxLoader);
    }
}

From source file:com.bfd.harpc.client.DefaultInvoker.java

@Override
public Object invoke(Method method, Object[] args) throws RpcException {
    T client = null;//  w ww . j a  v a 2s .  c  om
    ServerNode serverNode = null;
    Throwable exception = null;

    long startTime;
    for (int i = 0; i == 0 || i < retry + 1; i++) {
        startTime = System.currentTimeMillis();
        StatisticsInfo info = new StatisticsInfo();
        try {
            serverNode = loadBalancer.nextBackend();
            if (serverNode == null) {
                continue;
            }

            // System.out.println(serverNode);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Invoke to {}.", serverNode);
            }
            client = pool.borrowObject(serverNode);
            Object result = method.invoke(client, args);

            // load balancestatistics
            loadBalancer.requestResult(serverNode, RequestTracker.RequestResult.SUCCESS,
                    System.currentTimeMillis() - startTime);
            info.setSuccess(1);

            return result;
        } catch (InvocationTargetException ite) {// XXX:InvocationTargetException?method.invoke()
            Throwable cause = ite.getCause();
            if (cause != null) {
                if (cause instanceof TTransportException || cause instanceof AvroRemoteException) {
                    // load balancestatistics
                    loadBalancer.requestResult(serverNode, RequestTracker.RequestResult.TIMEOUT,
                            System.currentTimeMillis() - startTime);
                    hostSet.addDeadInstance(serverNode); // dead?
                    info.setFailure(1);
                    exception = cause;
                    try {
                        // XXX:pool,???
                        // ??socket?socket???
                        if (cause.getCause() != null && cause.getCause() instanceof SocketException) {
                            pool.clear(serverNode);
                        } else {
                            // XXX:??
                            pool.invalidateObject(serverNode, client);
                        }
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                    client = null; // ?returnpool
                } else {
                    loadBalancer.requestResult(serverNode, RequestTracker.RequestResult.FAILED,
                            System.currentTimeMillis() - startTime);
                    info.setFailure(1);
                    exception = cause;
                }
            } else {
                loadBalancer.requestResult(serverNode, RequestTracker.RequestResult.FAILED,
                        System.currentTimeMillis() - startTime);
                info.setFailure(1);
                exception = ite;
            }
        } catch (Throwable e) {
            // load balancestatistics
            loadBalancer.requestResult(serverNode, RequestTracker.RequestResult.FAILED,
                    System.currentTimeMillis() - startTime);
            info.setFailure(1);
            exception = e;
        } finally {
            if (client != null) {
                try {
                    pool.returnObject(serverNode, client);
                } catch (Exception e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            // ?
            if (monitor != null) {
                long usetime = System.currentTimeMillis() - startTime;
                info.setAvgtime(usetime);
                info.setMaxtime(usetime);
                info.setMintime(usetime);
                monitor.collect(clientNode, info);
            }
        }
    }
    throw new RpcException("Invoke error!", exception);
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalFileTestExecutionListener.java

@Override
public void afterTestMethod(TestContext testContext) throws Exception {
    if (isTestClassAssignableFromOwncloudLocalFileTest(testContext)) {
        ApplicationContext applicationContext = testContext.getApplicationContext();

        Class<?> testClass = testContext.getTestClass();
        Method testMethod = testContext.getTestMethod();

        DisposableBean localDataService = applicationContext.getBean(OwncloudLocalUserDataServiceImpl.class);
        localDataService.destroy();/*from w w  w  . j  av a2s  . c  o  m*/

        ResourceLoader resourceLoader = applicationContext;
        OwncloudProperties properties = applicationContext.getBean(OwncloudProperties.class);
        Resource target = resourceLoader.getResource(properties.getLocation());

        boolean hasSpecificResourceTest = false;
        for (Method method : testContext.getTestClass().getMethods()) {
            // is this Method annotated by @CompareResourceAfter
            CompareResourceAfter compareResourceAfter = AnnotationUtils.findAnnotation(method,
                    CompareResourceAfter.class);
            if (compareResourceAfter == null
                    || !StringUtils.equals(compareResourceAfter.value(), testMethod.getName())) {
                continue;
            }

            // a Method annotated by @Test cannot also be annotated by
            // @CompareResourceAfter
            if (AnnotationUtils.findAnnotation(method, Test.class) != null) {
                log.warn("Method {} of Class {} cannot be annotated by {} and {}", method.getName(),
                        testClass.getName(), CompareResourceAfter.class, Test.class);
                continue;
            }

            // the @CompareResourceAfter annotated Method must have exactly 2
            // Parameters of Type org.springframework.core.io.Resource
            if (method.getParameterCount() != 1) {
                log.warn("Method {} of Class {} is annotated by {} but has {} Parameters instead of 1",
                        method.getName(), testClass.getName(), CompareResourceAfter.class.getName(),
                        method.getParameterCount());
                continue;
            }
            boolean correctParameterTypes = true;
            for (Class<?> parameterClass : method.getParameterTypes()) {
                correctParameterTypes = correctParameterTypes
                        && Resource.class.isAssignableFrom(parameterClass);
            }
            if (!correctParameterTypes) {
                log.warn("Method {} of Class {} (annotated by {}) must have 1 Parameter of Type {}",
                        method.getName(), testClass.getName(), CompareResourceAfter.class.getName(),
                        Resource.class.getName());
                continue;
            }

            log.debug("Call the Resource Comparsion Method {} on Class {}", method.getName(),
                    testClass.getName());
            hasSpecificResourceTest = true;
            try {
                method.invoke(testContext.getTestInstance(), target);
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof Exception) {
                    throw (Exception) e.getCause();
                }
                throw (Error) e.getCause();
            }
        }

        if (!hasSpecificResourceTest && ((OwncloudLocalFileTest) testContext.getTestInstance())
                .isCheckAllResourcesAgainstOriginal()) {
            compareResourcesWithOriginalSource(resourceLoader, target);
        }
    }
}

From source file:org.apache.hadoop.hbase.regionserver.wal.SequenceFileLogWriter.java

@Override
public void init(FileSystem fs, Path path, Configuration conf, boolean overwritable) throws IOException {
    super.init(fs, path, conf, overwritable);
    boolean compress = initializeCompressionContext(conf, path);
    // Create a SF.Writer instance.
    try {//from w  w  w .jav  a  2s  .  co  m
        // reflection for a version of SequenceFile.createWriter that doesn't
        // automatically create the parent directory (see HBASE-2312)
        this.writer = (SequenceFile.Writer) SequenceFile.class
                .getMethod("createWriter",
                        new Class[] { FileSystem.class, Configuration.class, Path.class, Class.class,
                                Class.class, Integer.TYPE, Short.TYPE, Long.TYPE, Boolean.TYPE,
                                CompressionType.class, CompressionCodec.class, Metadata.class })
                .invoke(null,
                        new Object[] { fs, conf, path, HLogKey.class, WALEdit.class,
                                Integer.valueOf(FSUtils.getDefaultBufferSize(fs)),
                                Short.valueOf((short) conf.getInt("hbase.regionserver.hlog.replication",
                                        FSUtils.getDefaultReplication(fs, path))),
                                Long.valueOf(conf.getLong("hbase.regionserver.hlog.blocksize",
                                        FSUtils.getDefaultBlockSize(fs, path))),
                                Boolean.valueOf(false) /*createParent*/, SequenceFile.CompressionType.NONE,
                                new DefaultCodec(), createMetadata(conf, compress) });
    } catch (InvocationTargetException ite) {
        // function was properly called, but threw it's own exception
        throw new IOException(ite.getCause());
    } catch (Exception e) {
        // ignore all other exceptions. related to reflection failure
    }

    // if reflection failed, use the old createWriter
    if (this.writer == null) {
        LOG.debug("new createWriter -- HADOOP-6840 -- not available");
        this.writer = SequenceFile.createWriter(fs, conf, path, HLogKey.class, WALEdit.class,
                FSUtils.getDefaultBufferSize(fs),
                (short) conf.getInt("hbase.regionserver.hlog.replication",
                        FSUtils.getDefaultReplication(fs, path)),
                conf.getLong("hbase.regionserver.hlog.blocksize", FSUtils.getDefaultBlockSize(fs, path)),
                SequenceFile.CompressionType.NONE, new DefaultCodec(), null, createMetadata(conf, compress));
    } else {
        if (LOG.isTraceEnabled())
            LOG.trace("Using new createWriter -- HADOOP-6840");
    }

    this.writer_out = getSequenceFilePrivateFSDataOutputStreamAccessible();
    if (LOG.isTraceEnabled())
        LOG.trace("Path=" + path + ", compression=" + compress);
}

From source file:rb.app.QNTransientSCMSystem.java

/**
 * Override eval_theta_q_a in order to account for the affine terms
 * related to basis functions/*from  w ww . j  a  v a 2s  .co  m*/
 */
@Override
public double eval_theta_q_a(int q) {

    if (q < get_n_basis_functions()) {
        double theta_c_value = eval_theta_c();
        return current_RB_coeffs.getEntry(q) * theta_c_value;
    } else {

        Method meth;

        try {
            Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = double[].class;

            meth = mAffineFnsClass.getMethod("evaluateA", partypes);
        } catch (NoSuchMethodException nsme) {
            throw new RuntimeException("getMethod for evaluateA failed", nsme);
        }

        Double theta_val;
        try {
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(q - get_n_basis_functions());
            arglist[1] = current_parameters.getArray();

            Object theta_obj = meth.invoke(mTheta, arglist);
            theta_val = (Double) theta_obj;
        } catch (IllegalAccessException iae) {
            throw new RuntimeException(iae);
        } catch (InvocationTargetException ite) {
            throw new RuntimeException(ite.getCause());
        }

        return theta_val.doubleValue();
    }
}

From source file:net.sourceforge.vulcan.web.struts.actions.ManagePluginAction.java

private boolean validatePluginConfig(HttpServletRequest request, PluginConfigForm form) {
    final String focus = form.getFocus();
    final Object o;

    try {/* ww w  . j  a  v a 2s. c  o m*/
        try {
            o = PropertyUtils.getProperty(form, focus);
        } catch (InvocationTargetException e) {
            throw e.getCause();
        }
    } catch (Throwable e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    if (o instanceof PluginConfigDto) {
        try {
            ((PluginConfigDto) o).validate();
        } catch (ValidationException e) {
            final ActionMessages errors = new ActionMessages();

            convertExceptionToActionMessages(e, errors, focus);

            saveErrors(request, errors);
            return false;
        }
    }

    return true;
}