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:org.alfresco.error.AlfrescoRuntimeException.java

/**
 * Get the root cause.//from w  w  w .  jav  a  2 s.  c  o  m
 */
public Throwable getRootCause() {
    Throwable cause = this;
    for (Throwable tmp = this; tmp != null; tmp = cause.getCause()) {
        cause = tmp;
    }
    return cause;
}

From source file:com.mgmtp.jfunk.core.reporting.SimpleReporter.java

@Override
public void addResult(final ReportContext reportContext) {
    log.debug("Adding result to reporter '{}'", getName());

    StringBuilder sb = new StringBuilder(255);

    appendEscapedAndQuoted(sb, DATE_FORMAT.format(reportContext.getStartMillis()));
    appendEscapedAndQuoted(sb, TIME_FORMAT.format(reportContext.getStartMillis()));
    appendEscapedAndQuoted(sb, TIME_FORMAT.format(reportContext.getStopMillis()));
    appendEscapedAndQuoted(sb, DurationFormatUtils
            .formatDurationHMS(reportContext.getStopMillis() - reportContext.getStartMillis()));
    appendEscapedAndQuoted(sb, reportContext.getTestObjectName());
    appendEscapedAndQuoted(sb, reportContext.isSuccess() ? JFunkConstants.OK : JFunkConstants.ERROR);

    Throwable th = reportContext.getThrowable();
    if (th != null) {
        String msg = th.getMessage();

        Throwable root = th;
        while (root.getCause() != null) {
            root = root.getCause();/* www .  j  ava 2s.  c  o m*/
        }

        String rootMsg = root.getMessage();
        if (rootMsg != null && !rootMsg.equals(msg)) {
            msg += " - Root Message: " + rootMsg;
        }

        if (isBlank(msg)) {
            msg = th.getClass().getName();
        }

        appendEscapedAndQuoted(sb, msg);
    } else {
        appendEscapedAndQuoted(sb, null);
    }

    synchronized (this) {
        reportLines.add(sb.toString());
    }
}

From source file:com.vizury.videocache.core.CampaignExecutor.java

@SuppressWarnings("unchecked")
private void generateVideo(ProductDetail product) {
    JSONObject jReq = new JSONObject();
    jReq.put("type", "command");
    String jobID = threadId.toString() + "." + UUID.randomUUID().toString();
    jReq.put("job_id", jobID);
    jReq.put("landing_page_url", product.getLandingPageUrl());
    jReq.put("video_url", propertyMap.get("campaignProductListLocation"));
    jReq.put("campaign_id", campaignId);
    JSONArray products = new JSONArray();
    // Add main product
    JSONObject productInfo = new JSONObject();
    productInfo.put("img_url", product.getCdnUrl());
    productInfo.put("pname", product.getProductName());
    productInfo.put("pid", product.getProductId());
    products.add(productInfo);/*w w  w . j  a va2  s.  com*/
    // Add recommended products
    for (ProductDetail recProduct : product.getRecommendedProduct()) {
        JSONObject recProductInfo = new JSONObject();
        recProductInfo.put("img_url", recProduct.getCdnUrl());
        recProductInfo.put("pname", recProduct.getProductName());
        recProductInfo.put("pid", recProduct.getProductId());
        products.add(recProductInfo);
    }
    jReq.put("products", products);

    HttpRequest request = createJsonRequest(jReq.toJSONString());
    Future<HttpResponse> slaveAckF = client.apply(request);

    slaveAckF.addEventListener(new FutureEventListener<HttpResponse>() {
        public void onFailure(Throwable e) {
            System.out.println(e.getCause() + " : " + e.getMessage());
        }

        public void onSuccess(HttpResponse response) {
            System.out.println("[GeneratorMaster] Job ack received for job");
        }
    });
}

From source file:net.solarnetwork.node.setup.web.NodeAssociationController.java

@RequestMapping(value = "/importBackup", method = RequestMethod.POST)
public String importBackup(@RequestParam("file") MultipartFile file, HttpServletRequest request)
        throws IOException {
    final BackupManager manager = backupManagerTracker.service();
    if (manager == null) {
        request.getSession(true).setAttribute("errorMessageKey", "node.setup.restore.error.noBackupManager");
    } else {/*from w  w w . j a  va2 s .com*/
        try {
            manager.importBackupArchive(file.getInputStream());
            request.getSession(true).setAttribute("statusMessageKey", "node.setup.restore.success");
        } catch (Exception e) {
            log.error("Exception restoring backup archive", e);
            Throwable root = e;
            while (root.getCause() != null) {
                root = root.getCause();
            }
            request.getSession(true).setAttribute("errorMessageKey", "node.setup.restore.error.unknown");
            request.getSession(true).setAttribute("errorMessageParam0", root.getMessage());
        }
    }
    return "redirect:/associate";
}

From source file:de.ifgi.fmt.web.filter.RuntimeExceptionMapper.java

/**
 * /*w w  w.  j  a va  2 s .  c  om*/
 * @param t
 * @return
 */
@Override
public Response toResponse(Throwable t) {
    if (t instanceof WebApplicationException) {
        log.warn("Mapping Exception", t);
        return ((WebApplicationException) t).getResponse();
    }

    Throwable e = t;
    while (e != null) {
        if (e instanceof ServiceError) {
            return new ServiceErrorMapper().toResponse((ServiceError) e);
        }
        e = e.getCause();
    }

    log.info("Mapping Exception", t);
    ByteArrayOutputStream out = null;
    try {
        out = new ByteArrayOutputStream();
        t.printStackTrace(new PrintStream(out));
        return Response.serverError().entity(new String(out.toByteArray())).type(MediaType.TEXT_PLAIN).build();
    } catch (Throwable t2) {
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.netflix.hystrix.contrib.javanica.command.GenericCommand.java

/**
 * The fallback is performed whenever a command execution fails.
 * Also a fallback method will be invoked within separate command in the case if fallback method was annotated with
 * HystrixCommand annotation, otherwise current implementation throws RuntimeException and leaves the caller to deal with it
 * (see {@link super#getFallback()}).//  ww  w  .  j a v  a2  s  .c o  m
 * The getFallback() is always processed synchronously.
 * Since getFallback() can throw only runtime exceptions thus any exceptions are thrown within getFallback() method
 * are wrapped in {@link FallbackInvocationException}.
 * A caller gets {@link com.netflix.hystrix.exception.HystrixRuntimeException}
 * and should call getCause to get original exception that was thrown in getFallback().
 *
 * @return result of invocation of fallback method or RuntimeException
 */
@Override
protected Object getFallback() {
    if (getFallbackAction() != null) {
        final CommandAction commandAction = getFallbackAction();
        try {
            return process(new Action() {
                @Override
                Object execute() {
                    Object[] args = commandAction.getMetaHolder().getArgs();
                    if (commandAction.getMetaHolder().isExtendedFallback()) {
                        if (commandAction.getMetaHolder().isExtendedParentFallback()) {
                            args[args.length - 1] = getFailedExecutionException();
                        } else {
                            args = Arrays.copyOf(args, args.length + 1);
                            args[args.length - 1] = getFailedExecutionException();
                        }
                    } else {
                        if (commandAction.getMetaHolder().isExtendedParentFallback()) {
                            args = ArrayUtils.remove(args, args.length - 1);
                        }
                    }
                    return commandAction
                            .executeWithArgs(commandAction.getMetaHolder().getFallbackExecutionType(), args);
                }
            });
        } catch (Throwable e) {
            LOGGER.error(FallbackErrorMessageBuilder.create().append(commandAction, e).build());
            throw new FallbackInvocationException(e.getCause());
        }
    } else {
        return super.getFallback();
    }
}

From source file:gxu.software_engineering.shen10.market.core.GlobalExceptionHandler.java

/**
 * ??ajaxhtml~/*  ww w .  j av  a 2 s  .c o m*/
 * @param t ?
 * @return json or html depends on what the client wants!
 */
@ExceptionHandler(Throwable.class)
public ModelAndView exp(Throwable t) {
    L.error("?", t);
    ModelAndView mav = new ModelAndView(ERROR_PAGE);
    mav.addObject(STATUS, STATUS_NO);
    mav.addObject(MESSAGE, t.getMessage());
    if (t.getCause() != null) {
        mav.addObject(EXP_REASON, t.getCause().getMessage());
    } else {
        mav.addObject(EXP_REASON, UNKNOWN_REASON);
    }
    return mav;
}

From source file:com.redblackit.war.AppSecurityHttpTest.java

/**
 * Test GET using supplied URL, expectedTitle (to identify login or welcome page), and an indication of whether we
 * should authenticate OK, or not.// w  w w  .ja va2s . c  om
 *
 * @param url
 * @param expectedTitle
 * @param badClientCertificate
 * @throws Exception
 */
private void testGetUrl(final String url, final String expectedTitle, final boolean badClientCertificate)
        throws Exception {
    StringBuilder sb = new StringBuilder();
    sb.append(":url=").append(url).append(":expectedTitle=").append(expectedTitle)
            .append(":badClientCertificate=").append(badClientCertificate).append(":clientAuthMandatory=")
            .append(clientAuthMandatory);
    final String[] spropkeys = { "user.name", "clientAuthMandatory", "javax.net.ssl.keyStore",
            "javax.net.ssl.keyStorePassword", "javax.net.ssl.trustStore", "javax.net.ssl.trustStorePassword" };
    for (String spropkey : spropkeys) {
        sb.append("\n  [").append(spropkey).append("]=").append(System.getProperty(spropkey));
    }

    WebConversation conversation = new WebConversation();
    WebResponse response = null;
    try {
        response = conversation.getResponse(url);
        if (clientAuthMandatory && badClientCertificate) {
            Assert.fail("expected exception for bad certificate:but got response=" + response + sb);
        } else {
            Assert.assertNotNull("response" + sb, response);
            logger.info(response);

            String respUrl = response.getURL().toString();

            Assert.assertTrue("URL should start with '" + baseHttpsUrl + "' ... but was '" + respUrl + "'",
                    respUrl.startsWith(baseHttpsUrl));
            Assert.assertEquals("Title for response page" + sb, expectedTitle, response.getTitle().trim());
        }

    } catch (IOException se) {
        if (clientAuthMandatory && se instanceof SocketException) {
            logger.debug("expected exception" + sb, se);
            Throwable t = se.getCause();
            while (t instanceof SocketException) {
                t = t.getCause();
            }

            if (t != null) {
                logger.debug("root cause exception" + sb, t);
            }
        } else {
            logger.fatal("unexpected exception:" + sb, se);
            throw new RuntimeException("unexpected exception" + sb, se);
        }

    }
}

From source file:com.yy.kunka.core.workflow.error.DefaultErrorHandler.java

public void handleError(ProcessContext context, Throwable th) throws WorkflowException {
    context.stopProcess();/*from w w w .  j a v a 2s  .  com*/

    boolean shouldLog = true;
    Throwable cause = th;
    while (true) {
        if (unloggedExceptionClasses.contains(cause.getClass().getName())) {
            shouldLog = false;
            break;
        }
        cause = cause.getCause();
        if (cause == null) {
            break;
        }
    }
    if (shouldLog) {
        LOG.info("An error occurred during the workflow", th);
    }
    throw new WorkflowException(th);
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private String createEmailContent() throws IOException {
    int size = reportContextList.size();
    List<String> rowData = newArrayListWithCapacity(size);

    String reportRowTemplate = Resources.toString(getClass().getResource("email-report-row-template.html"),
            Charset.forName("UTF-8"));
    for (int i = 0; i < size; ++i) {
        ReportContext context = reportContextList.get(i);

        String rowContent = replacePlaceholderToken(reportRowTemplate, "counter", String.valueOf(i));
        rowContent = replacePlaceholderToken(rowContent, "start",
                TIMESTAMP_FORMAT.format(context.getStartMillis()));
        rowContent = replacePlaceholderToken(rowContent, "finish",
                TIMESTAMP_FORMAT.format(context.getStopMillis()));
        rowContent = replacePlaceholderToken(rowContent, "duration",
                DurationFormatUtils.formatDurationHMS(context.getStopMillis() - context.getStartMillis()));
        rowContent = replacePlaceholderToken(rowContent, "testobject", context.getTestObjectName());

        Throwable th = context.getThrowable();
        if (th == null) {
            rowContent = replacePlaceholderToken(rowContent, "image", "check");
            rowContent = replacePlaceholderToken(rowContent, "errormsg", "");
            rowContent = replacePlaceholderToken(rowContent, "style", "success");
        } else {/*from   ww  w  .j a va2 s .c  o  m*/
            rowContent = replacePlaceholderToken(rowContent, "image", "error");

            String msg = th.getMessage();

            Throwable root = th;
            while (root.getCause() != null) {
                root = root.getCause();
            }

            String rootMsg = root.getMessage();
            if (rootMsg != null && !rootMsg.equals(msg)) {
                msg += " - Root Message: " + rootMsg;
            }

            if (isBlank(msg)) {
                msg = th.getClass().getName();
            }

            rowContent = replacePlaceholderToken(rowContent, "errormsg", msg);
            rowContent = replacePlaceholderToken(rowContent, "style", "error");
        }

        rowData.add(rowContent);
    }

    String reportTemplate = Resources.toString(getClass().getResource("email-report-template.html"),
            Charset.forName("UTF-8"));
    reportTemplate = replacePlaceholderToken(reportTemplate, "timestamp", TIMESTAMP_FORMAT.format(new Date()),
            false);

    String reportData = on(LINE_SEPARATOR).join(rowData);
    reportTemplate = replacePlaceholderToken(reportTemplate, "rows", reportData, false);
    return reportTemplate;
}