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:com.ngdata.hbaseindexer.cli.AddOrUpdateIndexerCli.java

private void addExceptionMessages(Throwable throwable, StringBuilder builder) {
    Throwable cause = throwable;
    while (cause != null) {
        builder.append(cause.getMessage()).append('\n');
        cause = cause.getCause();
    }/*from ww w  .j a v  a 2s  . co m*/
}

From source file:com.chiorichan.configuration.serialization.ConfigurationSerialization.java

protected ConfigurationSerializable deserializeViaMethod(Method method, Map<String, Object> args) {
    try {/*  ww w.java 2  s. c o  m*/
        ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);

        if (result == null) {
            Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
                    "Could not call method '" + method.toString() + "' of " + clazz
                            + " for deserialization: method returned null");
        } else {
            return result;
        }
    } catch (Throwable ex) {
        Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
                "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
                ex instanceof InvocationTargetException ? ex.getCause() : ex);
    }

    return null;
}

From source file:gov.nih.nci.system.web.HTTPQuery.java

/**
 * Generates an HTML Error message based upon a given Exception
 * @param    Exception The exception that should be used to generate an HTML error message
 * @return   A string-based HTML error message containing the Exception message.
 *///from   w ww  . j a va2  s. c om
private String getHTMLErrorMsg(Exception ex) {

    StringBuilder sb = new StringBuilder();

    sb.append("<html>\n").append("<head>\n").append("<title>caCORE HTTP Servlet Error</title>\n")
            .append("</head>\n").append("<body>\n")
            .append("<table height=\"100%\" width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" >\n")
            .append("<tr valign=\"top\" align=\"left\">\n").append("<td valign=\"top\" align=\"left\">\n")

            .append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" >\n")
            .append("<tr valign=\"top\" align=\"left\">\n").append("<td valign=\"top\" align=\"left\">\n")
            .append("<tr>\n").append("<td valign=\"top\" align=\"left\">\n")
            .append("<b><font size=6>caCORE HTTP Servlet Error:</font></b>\n").append("</td>\n")
            .append("</tr>\n").append("<tr>\n").append("<td valign=\"top\" align=\"left\">\n")
            .append("<b><hr></b>\n").append("</td>\n").append("</tr>\n").append("<tr>\n")
            .append("<td valign=\"top\" align=\"left\">\n").append("<pre class=\"autoOverflow\">\n")
            .append("<font size=4 color=red><b><br><br>\n");

    String msg = ex.getMessage();
    Throwable tempEx = ex.getCause();
    while (tempEx != null) {
        msg += "<br><br>Caused by: " + tempEx.getMessage();
        tempEx = tempEx.getCause();
    }

    msg = org.apache.commons.lang.StringEscapeUtils.escapeHtml(msg);
    sb.append(msg);

    sb.append("</b></font>\n").append("</pre>\n").append("</td>\n").append("</tr>\n").append("</td>\n")
            .append("</tr>\n").append("</table>\n");

    return sb.toString();
}

From source file:nz.co.senanque.vaadinsupport.TouchkitHintsImpl.java

public void setCommonProperties(final AbstractField ret, final MaduraPropertyWrapper property,
        final MessageSource messageSource) {
    ret.setWidth(getWidth());/*from  w w w.ja  va  2  s .  co m*/
    ret.setReadThrough(true);
    ret.setPropertyDataSource(property);
    ret.setCaption(property.getLabel());
    ret.setRequired(property.isRequired());
    if (property.isRequired()) {
        ret.setInvalidCommitted(true);
    }
    ret.setReadOnly(property.isReadOnly());
    ret.setEnabled(property.isEnabled());
    ret.setVisible(property.isVisible());
    ret.setImmediate(m_forceImmediate);
    ret.setLocale(LocaleContextHolder.getLocale());
    MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(messageSource);
    ret.setDescription(
            messageSourceAccessor.getMessage(property.getDescription(), null, property.getDescription()));
    if (property.isNumeric()) {
        ret.addStyleName("v-textfield-align-right");
    }
    ret.setErrorHandler(new ComponentErrorHandler() {

        private static final long serialVersionUID = -1393935533100204195L;

        public boolean handleComponentError(ComponentErrorEvent event) {
            Throwable t = event.getThrowable();
            while (t != null) {
                if (t instanceof ValidationException) {
                    ret.setComponentError(new UserError(((ValidationException) t).getMessage()));
                    return true;
                }
                t = t.getCause();
            }
            return false;
        }
    });

}

From source file:com.jbrisbin.vpc.jobsched.sql.SqlMessageHandler.java

public SqlMessage handleMessage(final SqlMessage msg) throws Exception {
    log.debug("handling message: " + msg.toString());

    DataSource ds = appCtx.getBean(msg.getDatasource(), DataSource.class);
    JdbcTemplate tmpl = new JdbcTemplate(ds);

    String sql = msg.getSql();//from  ww  w  .  j  a  va 2s.  c  o  m
    CallableStatementCreator stmtCreator = null;
    CallableStatementCallback<SqlMessage> callback = null;
    if (sql.startsWith("plugin:")) {
        // Use a plugin to get the sql
        String pluginName = (sql.contains("?") ? sql.substring(7, sql.indexOf('?')) : sql.substring(7));
        final Plugin plugin = groovyPluginManager.getPlugin(pluginName);
        Map<String, Object> vars = new LinkedHashMap<String, Object>();
        vars.put("message", msg);
        vars.put("datasource", ds);
        vars.put("listen", groovyClosureFactory.createListenClosure(msg));
        vars.put("mapreduce", groovyClosureFactory.createMapReduceClosure(msg));
        plugin.setContext(vars);

        // Execute this plugin
        plugin.run();

        Object o = plugin.get("sql");
        if (null != o && o instanceof Closure) {
            sql = ((Closure) o).call(msg).toString();
        } else if (o instanceof String || o instanceof GString) {
            sql = o.toString();
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o) + " to SQL statement.");
        }
        msg.setSql(sql);

        o = plugin.get("statementCreator");
        if (null != o && o instanceof Closure) {
            stmtCreator = new CallableStatementCreator() {
                public CallableStatement createCallableStatement(Connection con) throws SQLException {
                    Object obj = ((Closure) plugin.get("statementCreator")).call(new Object[] { con, msg });
                    log.debug("from plugin statementCreator: " + String.valueOf(obj));
                    return (CallableStatement) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCreator. Define a closure named 'statementCreator' in your plugin.");
        }

        o = plugin.get("callback");
        if (null != o && o instanceof Closure) {
            callback = new CallableStatementCallback<SqlMessage>() {
                public SqlMessage doInCallableStatement(CallableStatement cs)
                        throws SQLException, DataAccessException {
                    Object obj = ((Closure) plugin.get("callback")).call(new Object[] { cs, msg });
                    log.debug("from plugin callback: " + String.valueOf(obj));
                    return (SqlMessage) obj;
                }
            };
        } else {
            throw new IllegalStateException("Can't convert " + String.valueOf(o)
                    + " to CallableStatementCallback. Define a closure named 'callback' in your plugin.");
        }
    } else {
        stmtCreator = new CallableStatementCreator() {
            public CallableStatement createCallableStatement(Connection connection) throws SQLException {
                CallableStatement stmt = connection.prepareCall(msg.getSql());
                List<Object> params = msg.getParams();
                if (null != params) {
                    int index = 1;
                    for (Object obj : params) {
                        stmt.setObject(index++, obj);
                    }
                }
                return stmt;
            }
        };
        callback = new CallableStatementCallback<SqlMessage>() {
            public SqlMessage doInCallableStatement(CallableStatement callableStatement)
                    throws SQLException, DataAccessException {
                if (null == msg.getResults().getData()) {
                    msg.getResults().setData(new ArrayList<List<Object>>());
                }
                if (callableStatement.execute()) {
                    ResultSet results = callableStatement.getResultSet();

                    // Pull out column names
                    ResultSetMetaData meta = results.getMetaData();
                    String[] columns = new String[meta.getColumnCount()];
                    for (int i = 1; i <= meta.getColumnCount(); i++) {
                        columns[i - 1] = meta.getColumnName(i);
                    }
                    msg.getResults().getColumnNames().addAll(Arrays.asList(columns));

                    int total = 0;
                    while (results.next()) {
                        List<Object> row = new ArrayList<Object>(columns.length);
                        for (int i = 1; i <= columns.length; i++) {
                            row.add(results.getObject(i));
                        }
                        msg.getResults().getData().add(row);
                        total++;
                    }
                    msg.getResults().setTotalRows(total);

                } else {
                    msg.getResults().getColumnNames().add("updateCount");
                    msg.getResults().setTotalRows(1);
                    List<Object> updCnt = new ArrayList<Object>(1);
                    updCnt.add(callableStatement.getUpdateCount());
                    msg.getResults().getData().add(updCnt);
                }
                return msg;
            }
        };
    }
    try {
        tmpl.setExceptionTranslator(appCtx.getBean(SQLExceptionTranslator.class));
    } catch (NoSuchBeanDefinitionException notfound) {
        // IGNORED
    }

    if (null != stmtCreator && null != callback) {
        try {
            tmpl.execute(stmtCreator, callback);
        } catch (Throwable t) {
            log.error(t.getMessage(), t);
            List<String> errors = new ArrayList<String>();
            errors.add(t.getMessage());
            Throwable cause = t.getCause();
            if (null != cause) {
                do {
                    errors.add(cause.getMessage());
                } while (null != (cause = cause.getCause()));
            }
            msg.getResults().setErrors(errors);
        }
    } else {
        log.warn("CallableStatementCreator and/or CallableStatementCallback where empty. "
                + "Make sure your plugin provides these under 'statementCreator' and 'callback' respectively.");
    }
    return msg;
}

From source file:org.apache.synapse.transport.nhttp.Axis2HttpRequest.java

/**
 * Start streaming the message into the Pipe, so that the contents could be read off the source
 * channel returned by getSourceChannel()
 *
 * @throws AxisFault on error//w  w w . ja  v a  2  s.c om
 */
public void streamMessageContents() throws AxisFault {

    if (log.isDebugEnabled()) {
        log.debug("Start streaming outgoing http request : [Message ID : " + msgContext.getMessageID() + "]");
        if (log.isTraceEnabled()) {
            log.trace("Message [Request Message ID : " + msgContext.getMessageID() + "] "
                    + "[Request Message Payload : [ " + msgContext.getEnvelope() + "]");
        }
    }

    NHttpConfiguration cfg = NHttpConfiguration.getInstance();
    int senderTimeout = cfg.getProperty(NhttpConstants.SO_TIMEOUT_SENDER, 60000);
    long startTime = System.currentTimeMillis();

    synchronized (this) {
        while (!readyToStream && !completed) {
            try {
                this.wait(senderTimeout + 10000);
                if ((startTime + senderTimeout + 5000) < System.currentTimeMillis()) {
                    handleException("Thread " + Thread.currentThread().getName()
                            + " is blocked longer than the send timeout when trying to send the message :"
                            + msgContext.getMessageID() + ". Releasing thread",
                            new AxisFault("Sender thread was not notified within send timeout"));
                }
            } catch (InterruptedException ignore) {
            }
        }
    }

    if (!completed) {
        OutputStream out = new ContentOutputStream(outputBuffer);
        try {
            if (msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
                writeMessageFromTempData(out);
            } else {
                if (chunked) {
                    messageFormatter.writeTo(msgContext, format, out, false);
                } else {
                    writeMessageFromTempData(out);
                }
            }
        } catch (Exception e) {
            Throwable t = e.getCause();
            if (t != null && t.getCause() != null && t.getCause() instanceof ClosedChannelException) {
                if (log.isDebugEnabled()) {
                    log.debug("Ignore closed channel exception, as the "
                            + "SessionRequestCallback handles this exception");
                }
            } else {
                Integer errorCode = msgContext == null ? null
                        : (Integer) msgContext.getProperty(NhttpConstants.ERROR_CODE);
                if (errorCode == null || errorCode == NhttpConstants.SEND_ABORT) {
                    if (log.isDebugEnabled()) {
                        log.debug("Remote server aborted request being sent, and responded");
                    }
                } else {
                    if (e instanceof AxisFault) {
                        throw (AxisFault) e;
                    } else {
                        handleException("Error streaming message context", e);
                    }
                }
            }
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                handleException("Error closing outgoing message stream", e);
            }
            setSendingCompleted(true);
        }
    }
}

From source file:nz.co.senanque.vaadinsupport.HintsImpl.java

public void setCommonProperties(final AbstractField ret, final MaduraPropertyWrapper property,
        final MessageSource messageSource) {
    ret.setWidth(getWidth());//from   w w w  .jav  a  2 s .  c om
    ret.setReadThrough(true);
    ret.setPropertyDataSource(property);
    ret.setCaption(property.getLabel());
    ret.setRequired(property.isRequired());
    if (property.isRequired()) {
        ret.setInvalidCommitted(true);
    }
    if (property.isReadOnly()) {
        ret.setReadOnly(true);
    }
    ret.setEnabled(property.isEnabled());
    ret.setVisible(property.isVisible());
    ret.setImmediate(m_forceImmediate);
    ret.setLocale(LocaleContextHolder.getLocale());
    MessageSourceAccessor messageSourceAccessor = new MessageSourceAccessor(messageSource);
    ret.setDescription(
            messageSourceAccessor.getMessage(property.getDescription(), null, property.getDescription()));
    if (property.isNumeric()) {
        ret.addStyleName("v-textfield-align-right");
    }
    ret.setErrorHandler(new ComponentErrorHandler() {

        private static final long serialVersionUID = -1393935533100204195L;

        public boolean handleComponentError(ComponentErrorEvent event) {
            Throwable t = event.getThrowable();
            while (t != null) {
                if (t instanceof ValidationException) {
                    ret.setComponentError(new UserError(((ValidationException) t).getMessage()));
                    return true;
                }
                t = t.getCause();
            }
            return false;
        }
    });

}

From source file:com.mgmtp.jfunk.core.scripting.ScriptExecutor.java

/**
 * Executes the specified Groovy script.
 *
 * @param script/*from w w  w .  j  a v  a 2s. co m*/
 *            the script file
 * @param scriptProperties
 *            properties that are set to the script engine's binding and thus will be available
 *            as variables in the Groovy script
 * @return the execution result, {@code true} if successful, {@code false} code
 */
public boolean executeScript(final File script, final Properties scriptProperties) {
    checkState(script.exists(), "Script file does not exist: %s", script);
    checkState(script.canRead(), "Script file is not readable: %s", script);

    Reader reader = null;
    boolean success = false;
    Throwable throwable = null;

    scriptScope.enterScope();
    ScriptContext ctx = scriptContextProvider.get();
    try {
        reader = Files.newReader(script, charset);

        ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("groovy");
        ctx.setScript(script);
        ctx.load(JFunkConstants.SCRIPT_PROPERTIES, false);
        ctx.registerReporter(new SimpleReporter());
        initGroovyCommands(scriptEngine, ctx);
        initScriptProperties(scriptEngine, scriptProperties);
        ScriptMetaData scriptMetaData = scriptMetaDataProvider.get();
        scriptMetaData.setScriptName(script.getPath());

        Date startDate = new Date();
        scriptMetaData.setStartDate(startDate);
        ctx.set(JFunkConstants.SCRIPT_START_MILLIS, String.valueOf(startDate.getTime()));

        eventBus.post(scriptEngine);
        eventBus.post(new BeforeScriptEvent(script.getAbsolutePath()));
        scriptEngine.eval(reader);
        success = true;
    } catch (IOException ex) {
        throwable = ex;
        log.error("Error loading script: " + script, ex);
    } catch (ScriptException ex) {
        throwable = ex;

        // Look up the cause hierarchy if we find a ModuleExecutionException.
        // We only need to log exceptions other than ModuleExecutionException because they
        // have already been logged and we don't want to pollute the log file any further.
        // In fact, other exception cannot normally happen.
        Throwable th = ex;
        while (!(th instanceof ModuleExecutionException)) {
            if (th == null) {
                // log original exception
                log.error("Error executing script: " + script, ex);
                success = false;
                break;
            }
            th = th.getCause();
        }
    } finally {
        try {
            ScriptMetaData scriptMetaData = scriptMetaDataProvider.get();

            Date endDate = new Date();
            scriptMetaData.setEndDate(endDate);
            ctx.set(JFunkConstants.SCRIPT_END_MILLIS, String.valueOf(endDate.getTime()));

            scriptMetaData.setThrowable(throwable);
            eventBus.post(new AfterScriptEvent(script.getAbsolutePath(), success));
        } finally {
            scriptScope.exitScope();
            closeQuietly(reader);
        }
    }

    return success;
}

From source file:io.druid.storage.oss.OssDataSegmentPuller.java

@Override
public Predicate<Throwable> shouldRetryPredicate() {
    // Yay! smart retries!
    return new Predicate<Throwable>() {
        @Override/*  w  w  w.j  a va 2  s  . c  om*/
        public boolean apply(Throwable e) {
            if (e == null) {
                return false;
            }
            if (OssUtils.OssRETRY.apply(e)) {
                return true;
            }
            // Look all the way down the cause chain, just in case something wraps it deep.
            return apply(e.getCause());
        }
    };
}

From source file:seava.j4e.web.controller.AbstractBaseController.java

/**
 * Exception/*from   w ww.j  a va2  s.  c om*/
 * 
 * @param e
 * @param response
 * @return
 * @throws IOException
 */
@ResponseBody
protected String handleManagedException(IErrorCode errorCode, Exception e, HttpServletResponse response,
        String outputType) throws IOException {

    IErrorCode err = errorCode;
    Map<String, String> result = new HashMap<String, String>();

    if (!(e instanceof BusinessException)) {
        e.printStackTrace();
    }
    if (err == null) {
        err = ErrorCode.G_RUNTIME_ERROR;
    }

    // if (e instanceof BusinessException) {
    // err = ((BusinessException) e).getErrorCode();
    // } else {
    // if (e.getCause() != null) {
    // Throwable t = e;
    // while (t.getCause() != null) {
    // t = t.getCause();
    // if (t instanceof BusinessException) {
    // err = ((BusinessException) t).getErrorCode();
    // break;
    // }
    // }
    // }
    // }

    result.put("err_group", err.getErrGroup());
    result.put("err_no", err.getErrNo() + "");
    result.put("err_msg", err.getErrMsg());

    // --------------------

    if (e.getCause() != null) {
        Throwable t = e;
        while (t.getCause() != null) {
            t = t.getCause();
        }

        if (t instanceof SQLException) {
            SQLException sqlException = (SQLException) t;
            result.put("msg", sqlException.getErrorCode() + " - " + sqlException.getSQLState() + " - "
                    + sqlException.getLocalizedMessage());

        } else {
            result.put("msg", t.getMessage());
        }

    }

    // ---------------------

    if (!result.containsKey("msg")) {
        result.put("msg", e.getMessage());
    } else {
        result.put("details", e.getMessage());
    }

    StringBuffer sb = new StringBuffer();

    if (outputType.matches("txt")) {
        sb.append(result.get("err_group") + "-" + result.get("err_no") + "\n||\n");
        sb.append(result.get("err_msg") + "\n||\n");
        sb.append(result.get("msg") + "\n||\n");
        sb.append(result.get("details") + "\n||\n");
    } else if (outputType.matches("html")) {
        sb.append("<html><body><div>" + result.get("msg") + "</div></body></html>");
    }

    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    response.getOutputStream().print(sb.toString());
    return null;
}