Example usage for java.lang Throwable getCause

List of usage examples for java.lang Throwable getCause

Introduction

In this page you can find the example usage for java.lang Throwable getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:coria2015.server.JsonRPCMethods.java

void handleJSON(JSONObject object) {
        String requestID = null;/*from  www  .j a va 2s  . c  o m*/

        try {
            requestID = object.get("id").toString();
            if (requestID == null)
                throw new RuntimeException("No id in JSON request");

            Object command = object.get("method");
            if (command == null)
                throw new RuntimeException("No method in JSON");

            if (!object.containsKey("params"))
                throw new RuntimeException("No params in JSON");
            Object p = object.get("params");

            Collection<MethodDescription> candidates = methods.get(command.toString());
            int max = Integer.MIN_VALUE;
            MethodDescription argmax = null;
            for (MethodDescription candidate : candidates) {
                int score = Integer.MAX_VALUE;
                for (int i = 0; i < candidate.types.length && score > max; i++) {
                    score = convert(p, candidate, score, null, i);
                }
                if (score > max) {
                    max = score;
                    argmax = candidate;
                }
            }

            if (argmax == null)
                throw new RuntimeException("Cannot find a matching method");

            Object[] args = new Object[argmax.arguments.length];
            for (int i = 0; i < args.length; i++) {
                int score = convert(p, argmax, 0, args, i);
                assert score > Integer.MIN_VALUE;
            }
            Object result = argmax.method.invoke(this, args);
            mos.endMessage(requestID, result);
        } catch (Throwable t) {
            LOGGER.warning("Error while handling JSON request");
            try {
                while (t.getCause() != null)
                    t = t.getCause();
                mos.error(requestID, 1, t.getMessage());
            } catch (IOException e) {
                LOGGER.severe("Could not send the return code");
            }
            return;
        }
    }

From source file:com.cisco.oss.foundation.loadbalancer.AbstractLoadBalancerStrategy.java

private void handleTimeout(final String apiName, final Throwable throwable) {
    if (throwable instanceof RequestTimeoutException) {
        throw (RequestTimeoutException) throwable;
    } else if (throwable instanceof SocketTimeoutException
            || (throwable != null && throwable.getMessage() != null
                    && (throwable.getMessage().contains("Inactivity timeout passed during read operation")
                            || (throwable.getCause() instanceof SocketTimeoutException)))) {

        final RequestTimeoutException requestTimeoutException = new RequestTimeoutException(
                "Error occurred while invoking the api: " + apiName, throwable.getCause());

        LOGGER.warn(requestTimeoutException.toString(), requestTimeoutException);

        throw requestTimeoutException;
    }/*  w  ww.  j a  va  2  s. co  m*/
}

From source file:com.vuze.android.remote.AndroidUtils.java

public static void showConnectionError(Activity activity, Throwable t, boolean allowContinue) {
    if (AndroidUtils.DEBUG) {
        Log.d(TAG, "showConnectionError " + AndroidUtils.getCompressedStackTrace(t, 0, 9));
    }//from   w  w w .  j  a va2s. c  om

    Throwable t2 = (t instanceof RPCException) ? t.getCause() : t;

    if ((t2 instanceof HttpHostConnectException) || (t2 instanceof UnknownHostException)) {
        String message = t.getMessage();
        if (AndroidUtils.DEBUG) {
            Log.d(TAG, "showConnectionError Yup " + message);
        }
        if (message != null && message.contains("pair.vuze.com")) {
            showConnectionError(activity, R.string.connerror_pairing, allowContinue);
            return;
        }
    }
    String message = "";
    while (t != null) {
        String newMessage = t.getMessage();
        if (newMessage != null && message.contains(newMessage)) {
            t = t.getCause();
            continue;
        }
        message += newMessage + "\n";
        Throwable tReplace = t;
        while (tReplace != null) {
            Class<?> cla = tReplace.getClass();
            String name = cla.getName();
            message = message.replaceAll(name + ": ", cla.getSimpleName() + ": ");
            tReplace = tReplace.getCause();
        }
        t = t.getCause();
    }
    showConnectionError(activity, message, allowContinue);
}

From source file:com.almende.eve.protocol.jsonrpc.formats.JSONRPCException.java

/**
 * Gets the throwable list./*from w w w.  j  ava2  s  .c o  m*/
 *
 * @return the throwable list
 */
@JsonIgnore
public List<Throwable> getThrowableList() {
    Throwable throwable = this;
    final List<Throwable> list = new ArrayList<Throwable>(3);
    while (throwable != null && list.contains(throwable) == false) {
        list.add(throwable);
        throwable = throwable.getCause();
    }
    return list;
}

From source file:jp.aegif.alfresco.online_webdav.GetMethod.java

protected void readContent(FileInfo realNodeInfo, ContentReader reader)
        throws IOException, WebDAVServerException {
    try {/*from www.j  ava  2  s. c  o m*/
        attemptReadContent(realNodeInfo, reader);
    } catch (ContentIOException e) {
        boolean logAsError = true;
        Throwable t = e;
        // MNT-8989: Traverse the exception cause hierarchy, if we find a SocketException at fault,
        // assume this is a dropped connection and do not log a stack trace.
        int levels = 0;
        while (t.getCause() != null) {
            if (t == t.getCause() || ++levels == MAX_RECURSE_ERROR_STACK) {
                // Avoid infinite loops.
                break;
            }
            t = t.getCause();
            if (t instanceof SocketException) {
                logAsError = false;
            }
        }

        if (logAsError && logger.isErrorEnabled()) {
            // Only log at ERROR level when not a SocketException as underlying cause.
            logger.error("Error while reading content", e);
        } else if (logger.isDebugEnabled()) {
            // Log other errors at DEBUG level.
            logger.debug("Error while reading content", e);
        }

        // Note no cause parameter supplied - avoid logging stack trace elsewhere.
        throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:com.owncloud.android.network.AdvancedSslSocketFactory.java

/**
 * Verifies the identity of the server. 
 * //w w  w.j a  va 2 s. c o  m
 * The server certificate is verified first.
 * 
 * Then, the host name is compared with the content of the server certificate using the current host name verifier, if any.
 * @param socket
 */
private void verifyPeerIdentity(String host, int port, Socket socket) throws IOException {
    try {
        CertificateCombinedException failInHandshake = null;
        /// 1. VERIFY THE SERVER CERTIFICATE through the registered TrustManager (that should be an instance of AdvancedX509TrustManager) 
        try {
            SSLSocket sock = (SSLSocket) socket; // a new SSLSession instance is created as a "side effect" 
            sock.startHandshake();

        } catch (RuntimeException e) {

            if (e instanceof CertificateCombinedException) {
                failInHandshake = (CertificateCombinedException) e;
            } else {
                Throwable cause = e.getCause();
                Throwable previousCause = null;
                while (cause != null && cause != previousCause
                        && !(cause instanceof CertificateCombinedException)) {
                    previousCause = cause;
                    cause = cause.getCause();
                }
                if (cause != null && cause instanceof CertificateCombinedException) {
                    failInHandshake = (CertificateCombinedException) cause;
                }
            }
            if (failInHandshake == null) {
                throw e;
            }
            failInHandshake.setHostInUrl(host);

        }

        /// 2. VERIFY HOSTNAME
        SSLSession newSession = null;
        boolean verifiedHostname = true;
        if (mHostnameVerifier != null) {
            if (failInHandshake != null) {
                /// 2.1 : a new SSLSession instance was NOT created in the handshake
                X509Certificate serverCert = failInHandshake.getServerCertificate();
                try {
                    mHostnameVerifier.verify(host, serverCert);
                } catch (SSLException e) {
                    verifiedHostname = false;
                }

            } else {
                /// 2.2 : a new SSLSession instance was created in the handshake
                newSession = ((SSLSocket) socket).getSession();
                if (!mTrustManager.isKnownServer((X509Certificate) (newSession.getPeerCertificates()[0]))) {
                    verifiedHostname = mHostnameVerifier.verify(host, newSession);
                }
            }
        }

        /// 3. Combine the exceptions to throw, if any
        if (!verifiedHostname) {
            SSLPeerUnverifiedException pue = new SSLPeerUnverifiedException(
                    "Names in the server certificate do not match to " + host + " in the URL");
            if (failInHandshake == null) {
                failInHandshake = new CertificateCombinedException(
                        (X509Certificate) newSession.getPeerCertificates()[0]);
                failInHandshake.setHostInUrl(host);
            }
            failInHandshake.setSslPeerUnverifiedException(pue);
            pue.initCause(failInHandshake);
            throw pue;

        } else if (failInHandshake != null) {
            SSLHandshakeException hse = new SSLHandshakeException("Server certificate could not be verified");
            hse.initCause(failInHandshake);
            throw hse;
        }

    } catch (IOException io) {
        try {
            socket.close();
        } catch (Exception x) {
            // NOTHING - irrelevant exception for the caller 
        }
        throw io;
    }
}

From source file:com.orange.mmp.message.jms.JMSMessageBroker.java

/**
 * Helper method used to send an error based on a Throwable 
 * //w w  w. j  a  v  a 2 s. co m
 * @param e The Throwable instance to send (only root cause is sent)
 * @param destination The destination of the error
 * @param sourceId The source ID of the message error (null for no source)
 * @throws MMPMessageException
 */
public void sendError(Throwable e, URI destination, Serializable sourceId) throws MMPMessageException {
    Message errorMessage = new Message();
    errorMessage.setId(sourceId);
    while (e.getCause() != null)
        e = e.getCause();
    errorMessage.setData(e);
    this.sendMessageTo(errorMessage, destination, null);
}

From source file:io.druid.metadata.SQLMetadataConnector.java

public final boolean isTransientException(Throwable e) {
    return e != null && (e instanceof SQLTransientException || e instanceof SQLRecoverableException
            || e instanceof UnableToObtainConnectionException || connectorIsTransientException(e)
            || (e instanceof SQLException && isTransientException(e.getCause()))
            || (e instanceof DBIException && isTransientException(e.getCause())));
}

From source file:io.wcm.caravan.io.http.impl.ribbon.RibbonHttpClientTest.java

@Test(expected = ClientException.class)
public void test_retryOnMultipleServerThrowing500WithoutChangingTheServer() throws ClientException {
    context.registerInjectActivateService(new CaravanHttpServiceConfig(),
            ImmutableMap.<String, Object>builder()
                    .put(CaravanHttpServiceConfig.SERVICE_ID_PROPERTY, SERVICE_NAME)
                    .put(CaravanHttpServiceConfig.RIBBON_HOSTS_PROPERTY,
                            Lists.newArrayList(defectServer1Host, defectServer2Host))
                    .put(CaravanHttpServiceConfig.RIBBON_MAXAUTORETRIES_PROPERTY, 4)
                    .put(CaravanHttpServiceConfig.RIBBON_MAXAUTORETRIESNEXTSERVER_PROPERTY, 0).build());
    try {/*from w w w . j  ava2  s . c o m*/
        Observable<CaravanHttpResponse> observable = client
                .execute(new CaravanHttpRequestBuilder(SERVICE_NAME).append(HTTP_200_URI).build());
        observable.toBlocking().single();
    } catch (Throwable ex) {
        int defectServer1count = defectServer1.countRequestsMatching(RequestPattern.everything()).getCount();
        int defectServer2count = defectServer2.countRequestsMatching(RequestPattern.everything()).getCount();
        assertEquals(5, defectServer1count + defectServer2count);
        assertTrue(defectServer1count == 0 || defectServer2count == 0);
        throw (ClientException) ex.getCause();
    }
}

From source file:io.druid.storage.hdfs.HdfsDataSegmentPuller.java

@Override
public Predicate<Throwable> shouldRetryPredicate() {
    return new Predicate<Throwable>() {
        @Override/*from w w w.j  av  a2  s .  co m*/
        public boolean apply(Throwable input) {
            if (input == null) {
                return false;
            }
            if (input instanceof HdfsIOException) {
                return true;
            }
            if (input instanceof IOException) {
                return true;
            }
            return apply(input.getCause());
        }
    };
}