Example usage for java.lang Throwable toString

List of usage examples for java.lang Throwable toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:net.solarnetwork.node.job.AbstractJob.java

/**
 * Helper method for logging a Throwable.
 * //w w w  .ja v  a 2 s .  c o  m
 * @param e
 *        the exception
 */
protected void logThrowable(Throwable e) {
    final String name = (getName() == null ? getClass().getSimpleName() : getName());
    Throwable root = e;
    while (root.getCause() != null) {
        root = root.getCause();
    }
    final Object[] logParams;
    if (log.isDebugEnabled()) {
        // include stack trace with log message in Debug
        logParams = new Object[] { root.getClass().getSimpleName(), name, e.toString(), e };
    } else {
        logParams = new Object[] { root.getClass().getSimpleName(), name, e.getMessage() };
    }
    log.error("{} in job {}: {}", logParams);
}

From source file:com.vmware.photon.controller.model.tasks.ProvisionComputeTaskService.java

private void failTask(Throwable e) {
    logWarning("Self patching to FAILED, task failure: %s", e.toString());
    sendSelfPatch(TaskStage.FAILED, ProvisionComputeTaskState.SubStage.FAILED, e);
}

From source file:com.googlecode.flyway.core.migration.DbMigrator.java

/**
 * Applies this migration to the database. The migration state and the execution time are updated accordingly.
 *
 * @param migration The migration to apply.
 * @return The row that was added to the metadata table.
 * @throws MigrationException when the migration failed.
 *///  w w  w. j  av  a2s.com
private MetaDataTableRow applyMigration(final Migration migration) throws MigrationException {
    MetaDataTableRow metaDataTableRow = new MetaDataTableRow(migration);

    LOG.info("Migrating to version " + migration.getVersion());

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    MigrationState state;
    try {
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(connectionForMigrations) {
            @Override
            protected void setNull(PreparedStatement preparedStatement, int parameterIndex)
                    throws SQLException {
                //No implementation needed
            }
        };
        new TransactionTemplate(connectionForMigrations).execute(new TransactionCallback<Void>() {
            public Void doInTransaction() {
                try {
                    migration.migrate(jdbcTemplate, dbSupport);
                } catch (SQLException e) {
                    throw new FlywayException("Migration failed!", e);
                }
                return null;
            }
        });
        LOG.debug("Successfully completed and committed DB migration to version "
                + migration.getVersion().toString());
        state = MigrationState.SUCCESS;
    } catch (Exception e) {
        LOG.error(e.toString());

        @SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (rootCause != null) {
            LOG.error("Caused by " + rootCause.toString());
        }
        state = MigrationState.FAILED;
    }

    stopWatch.stop();
    int executionTime = (int) stopWatch.getTotalTimeMillis();

    if (MigrationState.FAILED.equals(state) && dbSupport.supportsDdlTransactions()) {
        throw new MigrationException(migration.getVersion(), true);
    }
    LOG.debug(String.format("Finished migrating to version %s (execution time %s)", migration.getVersion(),
            TimeFormat.format(executionTime)));

    metaDataTableRow.update(executionTime, state);
    metaDataTable.insert(metaDataTableRow);
    LOG.debug("MetaData table successfully updated to reflect changes");

    return metaDataTableRow;
}

From source file:com.dilmus.dilshad.scabi.core.async.DComputeAsyncRun.java

public void run() {
    m_isDone = false;/* w  w w.java 2  s  .c  o  m*/
    if (true == m_isError)
        m_retriesTillNow = m_retriesTillNow + 1;
    m_isError = false;
    synchronized (m_computeNB) {
        try {
            m_computeNB.setTU(m_TU);
            m_computeNB.setSU(m_SU);

            doRun();
        } catch (Throwable e) {
            log.debug("run() Throwable : {}", e.toString());
            // m_computeNB is faulty only in the case of ClientProtocolException/NetworkException which 
            // is already handled in doRun() method
            // // // m_computeNB.setFaulty(true);

            log.debug("run() m_SU : {}", m_SU);
            String errorJson = DMJson.error(DMUtil.clientErrMsg(e));
            synchronized (m_config) {
                m_config.setResult(m_SU, errorJson);
            }
            m_isDone = true;
            m_isRetrySubmitted = false;
            if (false == m_isRunOnce) {
                m_isRunOnce = true;
            }

        }

    } // synchronized

}

From source file:com.ctrip.infosec.rule.executor.PreRulesExecutorService.java

/**
 * /*w  ww  .ja va2  s .c  o  m*/
 */
void executeParallel(final RiskFact fact, List<PreRule> matchedRules) {

    final StatelessPreRuleEngine statelessPreRuleEngine = SpringContextHolder
            .getBean(StatelessPreRuleEngine.class);
    final String _logPrefix = Contexts.getLogPrefix();
    final String _traceLoggerParentTransId = TraceLogger.getTransId();

    List runs1 = Lists.newArrayList();
    for (final PreRule rule : matchedRules) {

        // ???
        boolean matched = Configs.match(rule.getConditions(), rule.getConditionsLogical(), fact.eventBody);
        if (!matched) {
            continue;
        }

        final String packageName = rule.getRuleNo();
        runs1.add(new Callable<Boolean>() {

            @Override
            public Boolean call() throws Exception {
                RuleMonitorHelper.newTrans(fact, RuleMonitorType.PRE_RULE, packageName);
                TraceLogger.beginTrans(fact.eventId);
                TraceLogger.setParentTransId(_traceLoggerParentTransId);
                TraceLogger.setLogPrefix("[" + packageName + "]");
                Contexts.setPolicyOrRuleNo(packageName);
                long start = System.currentTimeMillis();
                try {
                    // add current execute ruleNo and logPrefix before execution
                    fact.ext.put(Constants.key_ruleNo, rule.getRuleNo());
                    fact.ext.put(Constants.key_isAsync, true);
                    if (rule.getRuleType() == RuleType.Script) {
                        statelessPreRuleEngine.execute(packageName, fact);
                    } else if (rule.getRuleType() == RuleType.Visual) {
                        PreActionEnums preAction = PreActionEnums.parse(rule.getPreAction());
                        if (preAction != null) {
                            Converter converter = converterLocator.getConverter(preAction);
                            converter.convert(preAction, rule.getPreActionFieldMapping(), fact,
                                    rule.getPreActionResultWrapper(), false);
                        }
                    }
                    // remove current execute ruleNo when finished execution.
                    fact.ext.remove(Constants.key_ruleNo);
                    fact.ext.remove(Constants.key_isAsync);
                } catch (Throwable ex) {
                    logger.warn(_logPrefix + "?. preRule: " + packageName
                            + ", exception: " + ex.getMessage());
                    TraceLogger.traceLog("EXCEPTION: " + ex.toString());
                } finally {
                    long handlingTime = System.currentTimeMillis() - start;
                    if (handlingTime > 100) {
                        logger.info(_logPrefix + "preRule: " + packageName + ", usage: " + handlingTime + "ms");
                    }
                    TraceLogger.traceLog("[" + packageName + "] usage: " + handlingTime + "ms");
                    TraceLogger.commitTrans();
                    RuleMonitorHelper.commitTrans2Trunk(fact);
                    Contexts.clearLogPrefix();
                }
                return true;
            }
        });

    }

    // run
    try {
        if (!runs1.isEmpty()) {
            List<Future<Boolean>> results = ParallelExecutorHolder.excutor.invokeAll(runs1, timeout,
                    TimeUnit.MILLISECONDS);
            for (Future f : results) {
                try {
                    if (!f.isDone()) {
                        f.cancel(true);
                    }
                } catch (Exception e) {
                    // ignored
                }
            }
        }
    } catch (Exception ex) {
        // ignored
    }
}

From source file:byps.http.HWireClientR.java

@Override
public void send(BMessage msg, BAsyncResult<BMessage> asyncResult) {
    if (log.isDebugEnabled())
        log.debug("send(" + msg + ", asyncResult=" + asyncResult);

    try {/* ww w .  ja va2 s . c  o  m*/

        final long messageId = msg.header.messageId;

        // Save result object for next long-poll
        if (log.isDebugEnabled())
            log.debug("map messageId=" + messageId + " to asyncResult=" + asyncResult);
        mapAsyncResults.put(messageId, asyncResult);

        for (int i = 0; i < 2; i++) {

            // If canceled, set BExceptionC.CLIENT_DIED to asyncResult 
            if (canceled) {
                terminateMessage(messageId, null);
                break;
            }

            // Find valid long-poll request object
            BAsyncResult<BMessage> asyncRequest = getNextLongpollRequestOrPushMessage(msg);

            // No long-poll found?
            if (asyncRequest == null) {

                // The message was pushed into pendingMessages_access_sync.
                // It will be sent in the next call to recvLongPoll. 
                break;
            }

            // Send the message
            try {

                asyncRequest.setAsyncResult(msg, null);
                break;

            } catch (Throwable e) {

                if (e.toString().indexOf("ClientAbortException") >= 0) {
                    terminateMessage(messageId, e);
                    break;
                } else {
                    // The underlying long-poll request has already timed out.
                    // Maybe there is another connection available.
                    // -> retry
                }

            }

        }

    } catch (Throwable e) {
        if (log.isWarnEnabled())
            log.warn("Failed to send reverse message.", e);
        asyncResult.setAsyncResult(null, e);
    }

    if (log.isDebugEnabled())
        log.debug(")send");
}

From source file:com.remobile.filetransfer.FileTransfer.java

/**
 * Create an error object based on the passed in errorCode
 *
 * @param errorCode the error//w w  w  .ja va  2 s.co  m
 * @return JSONObject containing the error
 */
private static JSONObject createFileTransferError(int errorCode, String source, String target, String body,
        Integer httpStatus, Throwable throwable) {
    JSONObject error = null;
    try {
        error = new JSONObject();
        error.put("code", errorCode);
        error.put("source", source);
        error.put("target", target);
        if (body != null) {
            error.put("body", body);
        }
        if (httpStatus != null) {
            error.put("http_status", httpStatus);
        }
        if (throwable != null) {
            String msg = throwable.getMessage();
            if (msg == null || "".equals(msg)) {
                msg = throwable.toString();
            }
            error.put("exception", msg);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return error;
}

From source file:com.haulmont.cuba.security.auth.AuthenticationServiceBean.java

protected LoginException wrapInLoginException(Throwable throwable) {
    //noinspection ThrowableResultOfMethodCallIgnored
    Throwable rootCause = ExceptionUtils.getRootCause(throwable);
    if (rootCause == null)
        rootCause = throwable;//from   w  ww  . j av a  2s .c om
    // send text only to avoid ClassNotFoundException when the client has no dependency to some library

    // todo rework, do not send exception messages they can contain sensitive configuration data

    return new InternalAuthenticationException(rootCause.toString());
}

From source file:com.wavemaker.runtime.server.ControllerBase.java

@Override
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {

    if (request == null) {
        throw new WMRuntimeException(MessageResource.SERVER_NOREQUEST);
    } else if (response == null) {
        throw new WMRuntimeException(MessageResource.SERVER_NORESPONSE);
    }/*w  w w  .j a  va  2s.co m*/

    ModelAndView ret;
    try {
        this.runtimeAccess.setStartTime(System.currentTimeMillis());
        // add logging
        StringBuilder logEntry = new StringBuilder();
        HttpSession session = request.getSession(false);
        if (session != null) {
            logEntry.append("session " + session.getId() + ", ");
        }
        logEntry.append("thread " + Thread.currentThread().getId());
        NDC.push(logEntry.toString());

        // default responses to the DEFAULT_ENCODING
        response.setCharacterEncoding(ServerConstants.DEFAULT_ENCODING);

        getServletEventNotifier().executeStartRequest();
        initializeRuntime(request, response);

        // execute the request
        ret = executeRequest(request, response);

        getServletEventNotifier().executeEndRequest();
    } catch (Throwable t) {
        this.logger.error(t.getMessage(), t);
        String message = t.getMessage();
        if (!StringUtils.hasLength(message)) {
            message = t.toString();
        }
        if (this.serviceResponse != null && !this.serviceResponse.isPollingRequest()
                && this.serviceResponse.getConnectionTimeout() > 0
                && System.currentTimeMillis()
                        - this.runtimeAccess.getStartTime() > (this.serviceResponse.getConnectionTimeout() - 3)
                                * 1000) {
            this.serviceResponse.addError(t);
        }
        return handleError(message, t);
    } finally {
        RuntimeAccess.setRuntimeBean(null);
        NDC.pop();
        NDC.remove();
    }

    return ret;
}

From source file:net.nicholaswilliams.java.licensing.licensor.interfaces.cli.ConsoleRSAKeyPairGenerator.java

public void run(String[] arguments) {
    this.processCommandLineOptions(arguments);

    try {/*  ww w. j a  v a  2s .c  om*/
        if (this.interactive) {
            this.device.printOutLn("Using interactive mode...");
            this.device.printOutLn();
            this.doInteractive();
        } else {
            this.doCommandLine();
        }
    } catch (RSA2048NotSupportedException e) {
        this.device.printErrLn(e.getLocalizedMessage());
        if (e.getCause() != null && e.getCause() instanceof NoSuchAlgorithmException)
            this.device.exit(51);
        else
            this.device.exit(52);
        return;
    } catch (AlgorithmNotSupportedException e) {
        this.device.printErrLn(e.getLocalizedMessage() + " Contact your system administrator for assistance.");
        this.device.exit(41);
        return;
    } catch (InappropriateKeyException e) {
        this.device.printErrLn(e.getLocalizedMessage() + " Contact your system administrator for assistance.");
        this.device.exit(42);
        return;
    } catch (InappropriateKeySpecificationException e) {
        this.device.printErrLn(e.getLocalizedMessage() + " Contact your system administrator for assistance.");
        this.device.exit(43);
        return;
    } catch (InterruptedException e) {
        // in theory, this error wouldn't actually get reached in this circumstance,
        // but we'll catch it just in case
        this.device.printErrLn("The system was interrupted while waiting for events to complete.");
        this.device.exit(44);
        return;
    } catch (IOException e) {
        this.device.printErrLn("An error occurred writing the key files to the file system. Analyze the error "
                + "below to determine what went wrong and fix it!");
        this.device.printErrLn(e.toString());
        e.printStackTrace();
        this.device.exit(21);
        return;
    } catch (Throwable t) {
        this.device.printErrLn(t.toString());
        t.printStackTrace();
        this.device.exit(-1);
        return;
    }

    this.device.exit(0);
}