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:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java

protected InitialDirContext buildInitialDirContext(final Map<String, String> config, final int pageSize,
        final AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    final AuthenticationDiagnostic effectiveDiagnostic = diagnostic != null ? diagnostic
            : new AuthenticationDiagnostic();

    final String securityPrincipal = config.get(Context.SECURITY_PRINCIPAL);
    final String providerURL = config.get(Context.PROVIDER_URL);

    if (this.isSSLSocketFactoryRequired(config)) {
        final KeyStore trustStore = this.initTrustStore();
        ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName());
    }//from   ww  w  . ja va2s.c  om

    try {
        // If a page size has been requested, use LDAP v3 paging
        if (pageSize > 0) {
            final InitialLdapContext ctx = new InitialLdapContext(new Hashtable<>(config), null);
            ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
            return ctx;
        } else {
            final InitialDirContext ret = new InitialDirContext(new Hashtable<>(config));
            final Object[] args = { providerURL, securityPrincipal };
            effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
            return ret;
        }
    } catch (final javax.naming.AuthenticationException ax) {
        final Object[] args1 = { securityPrincipal };
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);

        // wrong user/password - if we get this far the connection is O.K
        final Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.authentication", effectiveDiagnostic, args2, ax);
    } catch (final CommunicationException ce) {
        final Object[] args1 = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);

        final StringBuffer message = new StringBuffer();

        message.append(ce.getClass().getName() + ", " + ce.getMessage());

        Throwable cause = ce.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", effectiveDiagnostic, args, ce);
    } catch (final NamingException nx) {
        final Object[] args = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);

        final StringBuffer message = new StringBuffer();

        message.append(nx.getClass().getName() + ", " + nx.getMessage());

        Throwable cause = nx.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", effectiveDiagnostic, args1, nx);
    } catch (final IOException e) {
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);

        throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
    }
}

From source file:com.mirth.connect.client.ui.LibraryResourcesDialog.java

public LibraryResourcesDialog(Channel channel) {
    super(PlatformUI.MIRTH_FRAME, true);

    selectedResourceIds = new HashMap<Integer, Set<String>>();

    Set<String> channelResourceIds = channel.getProperties().getResourceIds();
    if (channelResourceIds == null) {
        channelResourceIds = new LinkedHashSet<String>();
    }//from   ww w. jav a 2s  .com
    selectedResourceIds.put(null, new LinkedHashSet<String>(channelResourceIds));

    Set<String> sourceResourceIds = ((SourceConnectorPropertiesInterface) channel.getSourceConnector()
            .getProperties()).getSourceConnectorProperties().getResourceIds();
    if (sourceResourceIds == null) {
        sourceResourceIds = new LinkedHashSet<String>();
    }
    selectedResourceIds.put(channel.getSourceConnector().getMetaDataId(),
            new LinkedHashSet<String>(sourceResourceIds));

    for (Connector destinationConnector : channel.getDestinationConnectors()) {
        Set<String> destinationResourceIds = ((DestinationConnectorPropertiesInterface) destinationConnector
                .getProperties()).getDestinationConnectorProperties().getResourceIds();
        if (destinationResourceIds == null) {
            destinationResourceIds = new LinkedHashSet<String>();
        }
        selectedResourceIds.put(destinationConnector.getMetaDataId(),
                new LinkedHashSet<String>(destinationResourceIds));
    }

    initComponents(channel);
    setPreferredSize(new Dimension(450, 444));
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setTitle("Library Resources");
    pack();
    setLocationRelativeTo(PlatformUI.MIRTH_FRAME);

    okButton.setEnabled(false);
    final String workingId = PlatformUI.MIRTH_FRAME.startWorking("Loading library resources...");

    SwingWorker<List<LibraryProperties>, Void> worker = new SwingWorker<List<LibraryProperties>, Void>() {

        @Override
        public List<LibraryProperties> doInBackground() throws ClientException {
            List<ResourceProperties> resourceProperties = PlatformUI.MIRTH_FRAME.mirthClient.getResources();
            List<LibraryProperties> libraryProperties = new ArrayList<LibraryProperties>();
            for (ResourceProperties resource : resourceProperties) {
                if (resource instanceof LibraryProperties) {
                    libraryProperties.add((LibraryProperties) resource);
                }
            }
            return libraryProperties;
        }

        @Override
        public void done() {
            try {
                List<LibraryProperties> resources = get();
                if (resources == null) {
                    resources = new ArrayList<LibraryProperties>();
                }

                Object[][] data = new Object[resources.size()][3];
                int i = 0;

                for (LibraryProperties properties : resources) {
                    data[i][SELECTED_COLUMN] = null;
                    data[i][PROPERTIES_COLUMN] = properties;
                    data[i][TYPE_COLUMN] = properties.getType();
                    i++;
                }

                ((RefreshTableModel) resourceTable.getModel()).refreshDataVector(data);

                treeTable.getSelectionModel().setSelectionInterval(0, 0);
                treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0));
                okButton.setEnabled(true);
            } catch (Throwable t) {
                if (t instanceof ExecutionException) {
                    t = t.getCause();
                }
                PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, t,
                        "Error loading library resources: " + t.toString());
            } finally {
                PlatformUI.MIRTH_FRAME.stopWorking(workingId);
            }
        }
    };

    worker.execute();

    setVisible(true);
}

From source file:org.openvpms.component.business.service.archetype.rule.ArchetypeRuleServiceTestCase.java

/**
 * Tests the behaviour of rules throwing exceptions.
 *
 * @param act    the act/*w  w w.  jav a2s  .  co  m*/
 * @param status the act status
 * @see #testException()
 */
private void checkException(Act act, String status) {
    long version = act.getVersion();
    try {
        act.setStatus(status);
        service.save(act);
        if (status != null) {
            fail("Expected save of act.simple to fail");
        }
    } catch (Throwable exception) {
        if (status == null) {
            fail("Expected save of act.simple to succeed");
        } else {
            // verify that the correct rule threw the exception
            assertEquals(status, act.getReason());

            // verify that an IllegalStateException is the root cause
            while (exception.getCause() != null) {
                exception = exception.getCause();
            }
            if (!(exception instanceof IllegalStateException)) {
                fail("Expected rule to throw IllegalStateException");
            }

            if (!act.isNew()) {
                // verify that the changes weren't saved
                Act original = reload(act);
                assertEquals(version, original.getVersion());
            }
        }
    }
}

From source file:com.microsoft.alm.plugin.idea.common.services.LocalizationServiceImpl.java

/**
 * Gets the localized exception message// ww  w.jav  a2s.c  om
 *
 * @param t
 * @return localized string
 */
public String getExceptionMessage(final Throwable t) {

    //get exception message
    String message = t.getLocalizedMessage();

    if (t instanceof LocalizedException) {
        final LocalizedException localizedException = (LocalizedException) t;
        final String key = localizedException.getMessageKey();
        if (keysMap.containsKey(key)) {
            message = getLocalizedMessage(keysMap.get(key),
                    (Object[]) localizedException.getMessageParameters());
        }
    }

    //exception message is not set
    //Use the message on the cause if there is one
    if (StringUtils.isEmpty(message) && t.getCause() != null) {
        if (t.getCause() instanceof LocalizedException) {
            final LocalizedException localizedException = (LocalizedException) t.getCause();
            final String key = localizedException.getMessageKey();
            if (keysMap.containsKey(key)) {
                message = getLocalizedMessage(keysMap.get(key),
                        (Object[]) localizedException.getMessageParameters());
            }
        } else {
            message = t.getCause().getLocalizedMessage();
        }
    }

    //No message on the exception and the cause, just use description from toString
    if (StringUtils.isEmpty(message)) {
        message = t.toString();
    }

    return message;
}

From source file:org.lendingclub.mercator.docker.SwarmScanner.java

protected boolean isNotFound(Throwable e) {
    if (e == null) {
        return false;
    }/*from  w  w w. ja va2  s  . c o m*/
    if (e instanceof NotFoundException || e instanceof com.github.dockerjava.api.exception.NotFoundException) {
        return true;
    }
    return isNotFound(e.getCause());
}

From source file:com.microsoft.windowsazure.messaging.e2etestapp.MainActivity.java

private void runTests() {
    TestGroup group = (TestGroup) mTestGroupSpinner.getSelectedItem();

    group.runTests(new TestExecutionCallback() {

        @Override/*from w w w  .  ja  v  a2  s. com*/
        public void onTestStart(TestCase test) {
            TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();
            adapter.notifyDataSetChanged();
            log("TEST START", test.getName());
        }

        @Override
        public void onTestGroupComplete(TestGroup group, List<TestResult> results) {
            log("TEST GROUP COMPLETED", group.getName() + " - " + group.getStatus().toString());
            logSeparator();
        }

        @Override
        public void onTestComplete(TestCase test, TestResult result) {
            Throwable e = result.getException();
            String exMessage = "-";
            if (e != null) {
                StringBuilder sb = new StringBuilder();
                while (e != null) {
                    sb.append(e.getClass().getSimpleName() + ": ");
                    sb.append(e.getMessage());
                    sb.append(" // ");
                    e = e.getCause();
                }

                exMessage = sb.toString();
            }

            final TestCaseAdapter adapter = (TestCaseAdapter) mTestCaseList.getAdapter();

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    adapter.notifyDataSetChanged();

                }

            });
            log("TEST LOG", test.getLog());
            log("TEST COMPLETED",
                    test.getName() + " - " + result.getStatus().toString() + " - Ex: " + exMessage);
            logSeparator();
        }
    });

}

From source file:de.tudarmstadt.lt.ltbot.writer.PlainTextDocumentWriter.java

protected File updateOuputFile() throws IOException {
    File basedir = getPath().getFile();
    File out = _current_file;// ww  w .j  a v  a 2  s  .c  om
    if (out == null || out.length() > _maxFileSizeBytes) {
        synchronized (_lck) {
            if (_current_stream != null)
                _current_stream.close();
            int not_ok_count = 0;
            while (not_ok_count > -1 && not_ok_count < 10) {
                for (++_num_current_file; out == null || out.exists(); ++_num_current_file) {
                    out = new File(basedir, getFilename());
                }
                _current_file = out;
                try {
                    _current_stream = openPrintToFileStream(_current_file);
                } catch (Throwable t) {
                    for (int i = 1; t != null && i < 10; i++) {
                        String message = String.format("Failed to open file for writing: '%s'. (%d %s:%s)",
                                _current_file.getAbsolutePath(), i, t.getClass().getSimpleName(),
                                t.getMessage());
                        LOG.log(Level.SEVERE, message, t);
                        t = t.getCause();
                    }
                    not_ok_count++;
                    if (not_ok_count >= 10)
                        throw new IOException(String.format(
                                "Failed to open file for writing: '%s'. I tried %d times but I give up now.",
                                _current_file.getAbsolutePath(), not_ok_count));
                    continue;
                }
                // break this loop, we're ok now
                not_ok_count = -1;
                break;
            }
        }
    }
    return out;
}

From source file:com.wavemaker.runtime.data.spring.SpringDataServiceManager.java

private Object runInTx(Task task, Object... input) {
    HibernateCallback action = new RunInHibernate(task, input);
    TransactionTemplate txTemplate = new TransactionTemplate(this.txMgr);
    boolean rollbackOnly = task instanceof DefaultRollback && !isTxRunning();
    RunInTx tx = new RunInTx(action, rollbackOnly);
    if (txLogger.isInfoEnabled()) {
        if (isTxRunning()) {
            txLogger.info("tx is running executing \"" + task.getName() + "\" in current tx");
        } else {/*from   w w w . ja  v a2  s .  c  o  m*/
            txLogger.info("no tx running, wrapping execution of \"" + task.getName() + "\" in tx");
            if (rollbackOnly) {
                txLogger.info("rollback enabled for \"" + task.getName() + "\"");
            }
        }
    }
    Object rtn = null;
    try {
        rtn = txTemplate.execute(tx);
    } catch (Throwable ex) {
        //The following logic intends to display a sensible message for the user when a column contains a value whose length
        //exceeds the maximum length allowed in the database.  The logic has been tested on MySQL, Postgres, Oracle and
        //SQLServer so far.
        if (ex.getCause() instanceof java.sql.BatchUpdateException) { //Oracle
            String msg = ((java.sql.BatchUpdateException) ex.getCause()).getNextException().getMessage();
            if (msg != null) {
                ex.printStackTrace();
                throw new WMRuntimeException(msg);
            }
        } else if (ex.getCause().getCause() instanceof java.sql.BatchUpdateException) { //Postgres
            java.sql.BatchUpdateException e = (java.sql.BatchUpdateException) ex.getCause().getCause();
            if (e != null && e.getMessage() != null) {
                ex.printStackTrace();
                throw new WMRuntimeException(e.getNextException().getMessage());
            }
        } else if (ex.getCause().getCause() != null) { //MySQL, SQLServer
            String msg = ex.getCause().getCause().getMessage();
            if (msg != null) {
                ex.printStackTrace();
                throw new WMRuntimeException(msg);
            }
        } else {
            throw new WMRuntimeException(ex);
        }
    }
    if (txLogger.isInfoEnabled()) {
        if (isTxRunning()) {
            txLogger.info("tx is running after execution of \"" + task.getName() + "\"");
        } else {
            txLogger.info("tx is not running after execution of \"" + task.getName() + "\"");
        }

    }
    return rtn;
}

From source file:at.wada811.android.library.demos.CrashExceptionHandler.java

/**
 * ?//w  w w. j a  v  a  2 s .  com
 * 
 * @param throwable
 * @return
 * @throws JSONException
 */
private JSONObject getExceptionInfo(Throwable throwable) throws JSONException {
    JSONObject json = new JSONObject();
    json.put("name", throwable.getClass().getName());
    json.put("message", throwable.getMessage());
    if (throwable.getStackTrace() != null) {
        // ExceptionStacktrace
        JSONArray exceptionStacktrace = new JSONArray();
        for (StackTraceElement element : throwable.getStackTrace()) {
            exceptionStacktrace.put("at " + LogUtils.getMetaInfo(element));
        }
        json.put("ExceptionStacktrace", exceptionStacktrace);
    }
    if (throwable.getCause() != null) {
        json.put("cause", throwable.getCause());
        // CausedStacktrace
        if (throwable.getCause().getStackTrace() != null) {
            JSONArray causedStacktrace = new JSONArray();
            for (StackTraceElement element : throwable.getCause().getStackTrace()) {
                causedStacktrace.put("at " + LogUtils.getMetaInfo(element));
            }
            json.put("CausedStacktrace", causedStacktrace);
        }
    }
    return json;
}

From source file:jef.database.DbUtils.java

/**
 * Runtime//  w  w  w.j av  a  2s .c om
 * 
 * @param e
 * @return
 */
public static RuntimeException toRuntimeException(Throwable e) {
    while (true) {
        if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        }
        if (e instanceof InvocationTargetException) {
            e = e.getCause();
            continue;
        }
        if (e instanceof Error) {
            throw (Error) e;
        }
        if (e instanceof SQLException) {
            return toRuntimeException((SQLException) e);
        }
        return new IllegalStateException(e);
    }
}