Example usage for java.lang Throwable getStackTrace

List of usage examples for java.lang Throwable getStackTrace

Introduction

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

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:net.cbtltd.rest.yandex.A_Handler.java

/**
 * Transfer accommodation products./*from  ww w.  j  av  a 2  s  .  c o m*/
 * 
 * @param sqlSession the current SQL session.
 */
@Override
public synchronized void readProducts() {
    String message = "Read Products from Yandex xml";
    LOG.debug(message);
    Date version = new Date();
    HashSet<String> productsProceeded = new HashSet<String>();

    try {
        document = parseXML(new File(System.getProperty("user.dir") + "\\doc\\advToAbook.xml"));
        //document = parseXML(new URL("http://staytoday.ru/advToAbook.xml"));
        ns = document.getRootElement().getNamespace();

        //testStayToday();

        //createOrUpdateProducts(productsProceeded);

        //    readHousePropertyCodes();
        //    updateInactiveProducts(productsProceeded);

        readDescriptions();
        //readImages();

        //    setLocation();

        //readPrices();
        //readFees();
        //    readSchedule();

        //MonitorService.monitor(message, version);
    } catch (Throwable x) {
        x.printStackTrace();
        LOG.error(x.getStackTrace());
    }
}

From source file:org.unitime.timetable.filter.QueryLogFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    String sessionId = null;// w  w w.  jav  a 2s  .c o  m
    String userId = null;
    try {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest r = (HttpServletRequest) request;
            sessionId = r.getSession().getId();
            UserContext user = getUser();
            if (user != null)
                userId = user.getTrueExternalUserId();
        }
    } catch (IllegalStateException e) {
    }

    long t0 = JProf.currentTimeMillis();
    Throwable exception = null;
    try {
        chain.doFilter(request, response);
    } catch (Throwable t) {
        exception = t;
    }
    long t1 = JProf.currentTimeMillis();

    if (exception == null) {
        Object ex = request.getAttribute("__exception");
        if (ex != null && ex instanceof Throwable)
            exception = (Throwable) ex;
    }

    if (request instanceof HttpServletRequest) {
        HttpServletRequest r = (HttpServletRequest) request;
        QueryLog q = new QueryLog();
        String uri = r.getRequestURI();
        if (uri.indexOf('/') >= 0)
            uri = uri.substring(uri.lastIndexOf('/') + 1);
        if (uri.endsWith(".do"))
            q.setType(QueryLog.Type.STRUCTS.ordinal());
        else if (uri.endsWith(".gwt"))
            q.setType(QueryLog.Type.GWT.ordinal());
        else
            q.setType(QueryLog.Type.OTHER.ordinal());
        q.setUri(uri);
        q.setTimeStamp(new Date());
        q.setTimeSpent(t1 - t0);
        q.setSessionId(sessionId);
        q.setUid(userId);
        try {
            if (sessionId == null)
                q.setSessionId(r.getSession().getId());
            if (userId == null) {
                UserContext user = getUser();
                if (user != null)
                    q.setUid(user.getTrueExternalUserId());
            }
        } catch (IllegalStateException e) {
        }
        GwtCallInfo callInfo = GwtDispatcherServlet.getLastQuery();
        if (callInfo != null) {
            q.setQuery(callInfo.getQuery());
            q.setUri(q.getUri() + ": " + callInfo.getTarget());
        } else if (ApplicationProperty.QueryLogJSON.isTrue()) {
            try {
                Map<String, Object> params = new HashMap<String, Object>();
                for (Map.Entry<String, String[]> e : r.getParameterMap().entrySet()) {
                    if ("password".equals(e.getKey()) || "noCacheTS".equals(e.getKey()))
                        continue;
                    if (e.getValue() == null || e.getValue().length == 0)
                        continue;
                    if (e.getValue().length == 1)
                        params.put(e.getKey(), e.getValue()[0]);
                    else
                        params.put(e.getKey(), e.getValue());
                }
                q.setQuery(iGson.toJson(params));
            } catch (Throwable t) {
            }
        } else {
            String params = "";
            for (Enumeration e = r.getParameterNames(); e.hasMoreElements();) {
                String n = (String) e.nextElement();
                if ("password".equals(n) || "noCacheTS".equals(n))
                    continue;
                if (!params.isEmpty())
                    params += "&";
                params += n + "=" + r.getParameter(n);
            }
            if (!params.isEmpty())
                q.setQuery(params);
        }
        if (exception != null) {
            Throwable t = exception;
            String ex = "";
            while (t != null) {
                String clazz = t.getClass().getName();
                if (clazz.indexOf('.') >= 0)
                    clazz = clazz.substring(1 + clazz.lastIndexOf('.'));
                if (!ex.isEmpty())
                    ex += "\n";
                ex += clazz + ": " + t.getMessage();
                if (t.getStackTrace() != null && t.getStackTrace().length > 0)
                    ex += " (at " + t.getStackTrace()[0].getFileName() + ":"
                            + t.getStackTrace()[0].getLineNumber() + ")";
                t = t.getCause();
            }
            if (!ex.isEmpty())
                q.setException(ex);
        }
        if (!iExclude.contains(q.getUri()) || q.getException() != null) {
            if (iSaver != null)
                iSaver.add(q);
        }
    }

    if (exception != null) {
        if (exception instanceof ServletException)
            throw (ServletException) exception;
        if (exception instanceof IOException)
            throw (IOException) exception;
        if (exception instanceof RuntimeException)
            throw (RuntimeException) exception;
        throw new ServletException(exception);
    }
}

From source file:lucee.runtime.config.ConfigImpl.java

public ORMEngine getORMEngine(PageContext pc) throws PageException {
    String name = pc.getApplicationContext().getName();

    ORMEngine engine = ormengines.get(name);
    if (engine == null) {
        //try {// w ww. j a v  a2  s.c  o  m
        Throwable t = null;

        try {
            engine = (ORMEngine) ClassUtil.loadInstance(ormEngineClass);
            engine.init(pc);
        } catch (ClassException ce) {
            t = ce;
        } catch (NoClassDefFoundError ncfe) {
            t = ncfe;
        }

        if (t != null) {
            ApplicationException ae = new ApplicationException("cannot initialize ORM Engine ["
                    + ormEngineClass.getName() + "], make sure you have added all the required jar files");

            ae.setStackTrace(t.getStackTrace());
            ae.setDetail(t.getMessage());

        }
        ormengines.put(name, engine);
        /*}
        catch (PageException pe) {
           throw pe;
        }*/
    }

    return engine;
}

From source file:com.sentaroh.android.SMBSync2.SyncTaskUtility.java

@SuppressWarnings("unused")
private void testAuth(final NtlmPasswordAuthentication auth, final String host, String port,
        final NotifyEvent ntfy) {
    final UncaughtExceptionHandler defaultUEH = Thread.currentThread().getUncaughtExceptionHandler();
    Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//from   w w w.ja va  2s  .c o m
        public void uncaughtException(Thread thread, Throwable ex) {
            Thread.currentThread().setUncaughtExceptionHandler(defaultUEH);
            ex.printStackTrace();
            StackTraceElement[] st = ex.getStackTrace();
            String st_msg = "";
            for (int i = 0; i < st.length; i++) {
                st_msg += "\n at " + st[i].getClassName() + "." + st[i].getMethodName() + "("
                        + st[i].getFileName() + ":" + st[i].getLineNumber() + ")";
            }
            String end_msg = ex.toString() + st_msg;
            ntfy.notifyToListener(true, new Object[] { end_msg });
            // re-throw critical exception further to the os (important)
            //                defaultUEH.uncaughtException(thread, ex);
        }
    });

    String err_msg = null;
    SmbFile sf = null;
    SmbFile[] lf = null;
    String url = "";
    if (port.equals("")) {
        url = "smb://" + host + "/IPC$/";
    } else {
        url = "smb://" + host + ":" + port + "/IPC$/";
    }
    //      Log.v("","url="+url);
    try {
        sf = new SmbFile(url, auth);
        sf.connect();
        util.addDebugMsg(1, "I",
                "Test logon completed, host=" + host + ", port=" + port + ", user=" + auth.getUsername());
    } catch (SmbException e) {
        String[] e_msg = NetworkUtil.analyzeNtStatusCode(e, mContext, url, auth.getUsername());
        err_msg = e_msg[0];
        util.addDebugMsg(1, "I", "Test logon failed." + "\n" + err_msg);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Thread.currentThread().setUncaughtExceptionHandler(defaultUEH);
    ntfy.notifyToListener(true, new Object[] { err_msg });
}

From source file:org.apache.hadoop.hbase.coprocessor.transactional.SsccRegionEndpoint.java

/**
 * Formats the throwable stacktrace to a string
 * @param Throwable e//from  w  w  w  .  j a v  a 2  s .co m
 * @return String 
 */
public String stackTraceToString(Throwable e) {
    StringBuilder sb = new StringBuilder();
    for (StackTraceElement element : e.getStackTrace()) {
        sb.append(element.toString());
        sb.append("\n");
    }
    return sb.toString();
}

From source file:org.auraframework.test.WebDriverTestCase.java

/**
 * Gather up useful info to add to a test failure. try to get
 * <ul>//from ww  w .ja  v  a  2  s  .co  m
 * <li>any client js errors</li>
 * <li>last known js test function</li>
 * <li>running/waiting</li>
 * <li>a screenshot</li>
 * </ul>
 * 
 * @param originalErr the test failure
 * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info
 */
private Throwable addAuraInfoToTestFailure(Throwable originalErr) {
    StringBuffer description = new StringBuffer();
    if (originalErr != null) {
        String msg = originalErr.getMessage();
        if (msg != null) {
            description.append(msg);
        }
    }
    description.append(String.format("\nBrowser: %s", currentBrowserType));
    if (auraUITestingUtil != null) {
        description.append("\nUser-Agent: " + auraUITestingUtil.getUserAgent());
    }
    if (currentDriver == null) {
        description.append("\nTest failed before WebDriver was initialized");
    } else {
        description.append("\nWebDriver: " + currentDriver);
        description.append("\nJS state: ");
        try {
            String dump = (String) auraUITestingUtil
                    .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
            if (dump.isEmpty()) {
                description.append("no errors detected");
            } else {
                description.append(dump);
            }
        } catch (Throwable t) {
            description.append(t.getMessage());
        }

        String screenshotsDirectory = System.getProperty("screenshots.directory");
        if (screenshotsDirectory != null) {
            String img = getBase64EncodedScreenshot(originalErr, true);
            if (img == null) {
                description.append("\nScreenshot: {not available}");
            } else {
                String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png";
                File path = new File(screenshotsDirectory + "/" + fileName);
                try {
                    path.getParentFile().mkdirs();
                    byte[] bytes = Base64.decodeBase64(img.getBytes());
                    FileOutputStream fos = new FileOutputStream(path);
                    fos.write(bytes);
                    fos.close();
                    String baseUrl = System.getProperty("screenshots.baseurl");
                    description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName));
                } catch (Throwable t) {
                    description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage()));
                }
            }
        }

        try {
            description.append("\nApplication cache status: ");
            description.append(auraUITestingUtil.getRawEval(
                    "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;")
                    .toString());
        } catch (Exception ex) {
            description.append("error calculating status: " + ex);
        }
        description.append("\n");
        if (SauceUtil.areTestsRunningOnSauce()) {
            String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver);
            description.append("\nSauceLabs-recording: ");
            description.append((linkToJob != null) ? linkToJob : "{not available}");
        }
    }

    // replace original exception with new exception with additional info
    Throwable newFailure;
    if (originalErr instanceof AssertionFailedError) {
        newFailure = new AssertionFailedError(description.toString());
    } else {
        description.insert(0, originalErr.getClass() + ": ");
        newFailure = new UnexpectedError(description.toString(), originalErr.getCause());
    }
    newFailure.setStackTrace(originalErr.getStackTrace());
    return newFailure;
}

From source file:org.auraframework.test.util.WebDriverTestCase.java

/**
 * Gather up useful info to add to a test failure. try to get
 * <ul>//  w  w  w .  j a v  a 2s  .  com
 * <li>any client js errors</li>
 * <li>last known js test function</li>
 * <li>running/waiting</li>
 * <li>a screenshot</li>
 * </ul>
 * 
 * @param originalErr the test failure
 * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info
 */
private Throwable addAuraInfoToTestFailure(Throwable originalErr) {
    StringBuffer description = new StringBuffer();
    if (originalErr != null) {
        String msg = originalErr.getMessage();
        if (msg != null) {
            description.append(msg);
        }
    }

    description.append(String.format("\nBrowser: %s", currentBrowserType));
    if (auraUITestingUtil != null) {
        description.append("\nUser-Agent: " + auraUITestingUtil.getUserAgent());
    }
    if (currentDriver == null) {
        description.append("\nTest failed before WebDriver was initialized");
    } else {

        if (this instanceof PerfExecutorTest) {
            JSONArray json = this.getLastCollectedMetrics();
            description.append("\nPerfMetrics: " + json + ';');
        }

        description.append("\nWebDriver: " + currentDriver);
        description.append("\nJS state: ");
        try {
            String dump = (String) auraUITestingUtil
                    .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
            if (dump.isEmpty()) {
                description.append("no errors detected");
            } else {
                description.append(dump);
            }
        } catch (Throwable t) {
            description.append(t.getMessage());
        }

        String screenshotsDirectory = System.getProperty("screenshots.directory");
        if (screenshotsDirectory != null) {
            String img = getBase64EncodedScreenshot(originalErr, true);
            if (img == null) {
                description.append("\nScreenshot: {not available}");
            } else {
                String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png";
                File path = new File(screenshotsDirectory + "/" + fileName);
                try {
                    path.getParentFile().mkdirs();
                    byte[] bytes = Base64.decodeBase64(img.getBytes());
                    FileOutputStream fos = new FileOutputStream(path);
                    fos.write(bytes);
                    fos.close();
                    String baseUrl = System.getProperty("screenshots.baseurl");
                    description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName));
                } catch (Throwable t) {
                    description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage()));
                }
            }
        }

        try {
            description.append("\nApplication cache status: ");
            description.append(auraUITestingUtil.getRawEval(
                    "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;")
                    .toString());
        } catch (Exception ex) {
            description.append("error calculating status: " + ex);
        }
        description.append("\n");
        if (SauceUtil.areTestsRunningOnSauce()) {
            String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver);
            description.append("\nSauceLabs-recording: ");
            description.append((linkToJob != null) ? linkToJob : "{not available}");
        }
    }

    // replace original exception with new exception with additional info
    Throwable newFailure;
    if (originalErr instanceof AssertionFailedError) {
        newFailure = new AssertionFailedError(description.toString());
    } else {
        description.insert(0, originalErr.getClass() + ": ");
        newFailure = new UnexpectedError(description.toString(), originalErr.getCause());
    }
    newFailure.setStackTrace(originalErr.getStackTrace());
    return newFailure;
}

From source file:org.auraframework.integration.test.util.WebDriverTestCase.java

/**
 * Gather up useful info to add to a test failure. try to get
 * <ul>/*www .j a  v  a2s.com*/
 * <li>any client js errors</li>
 * <li>last known js test function</li>
 * <li>running/waiting</li>
 * <li>a screenshot</li>
 * </ul>
 *
 * @param originalErr the test failure
 * @throws Throwable a new AssertionFailedError or UnexpectedError with the original and additional info
 */
private Throwable addAuraInfoToTestFailure(Throwable originalErr) {
    StringBuffer description = new StringBuffer();
    if (originalErr != null) {
        String msg = originalErr.getMessage();
        if (msg != null) {
            description.append(msg);
        }
    }

    description.append(String.format("\nBrowser: %s", currentBrowserType));
    if (getAuraUITestingUtil() != null) {
        description.append("\nUser-Agent: " + getAuraUITestingUtil().getUserAgent());
    }
    if (currentDriver == null) {
        description.append("\nTest failed before WebDriver was initialized");
    } else {

        if (this instanceof PerfExecutorTestCase) {
            JSONArray json = this.getLastCollectedMetrics();
            description.append("\nPerfMetrics: " + json + ';');
        }

        description.append("\nWebDriver: " + currentDriver);
        description.append("\nJS state: ");
        try {
            String dump = (String) getAuraUITestingUtil()
                    .getRawEval("return (window.$A && $A.test && $A.test.getDump())||'';");
            if (dump.isEmpty()) {
                description.append("no errors detected");
            } else {
                description.append(dump);
            }
        } catch (Throwable t) {
            description.append(t.getMessage());
        }

        String screenshotsDirectory = System.getProperty("screenshots.directory");
        if (screenshotsDirectory != null) {
            String screenshot = null;
            TakesScreenshot ts = (TakesScreenshot) currentDriver;
            try {
                screenshot = ts.getScreenshotAs(OutputType.BASE64);
            } catch (WebDriverException e) {
                description.append(String.format("%nScreenshot: {capture error: %s}", e.getMessage()));
            }

            if (screenshot != null) {
                String fileName = getClass().getName() + "." + getName() + "_" + currentBrowserType + ".png";
                try {
                    File path = new File(screenshotsDirectory + "/" + fileName);
                    path.getParentFile().mkdirs();
                    byte[] bytes = Base64.decodeBase64(screenshot.getBytes());
                    FileOutputStream fos = new FileOutputStream(path);
                    fos.write(bytes);
                    fos.close();
                    String baseUrl = System.getProperty("screenshots.baseurl");
                    description.append(String.format("%nScreenshot: %s/%s", baseUrl, fileName));
                } catch (Throwable t) {
                    description.append(String.format("%nScreenshot: {save error: %s}", t.getMessage()));
                }
            }
        }

        try {
            description.append("\nApplication cache status: ");
            description.append(getAuraUITestingUtil().getRawEval(
                    "var cache=window.applicationCache;return (cache===undefined || cache===null)?'undefined':cache.status;")
                    .toString());
        } catch (Exception ex) {
            description.append("error calculating status: " + ex);
        }
        description.append("\n");
        if (SauceUtil.areTestsRunningOnSauce()) {
            String linkToJob = SauceUtil.getLinkToPublicJobInSauce(currentDriver);
            description.append("\nSauceLabs-recording: ");
            description.append((linkToJob != null) ? linkToJob : "{not available}");
        }
    }

    // replace original exception with new exception with additional info
    Throwable newFailure;
    if (originalErr instanceof AssertionFailedError) {
        newFailure = new AssertionFailedError(description.toString());
    } else {
        description.insert(0, originalErr.getClass() + ": ");
        newFailure = new UnexpectedError(description.toString(), originalErr.getCause());
    }
    newFailure.setStackTrace(originalErr.getStackTrace());
    return newFailure;
}

From source file:org.soitoolkit.commons.studio.components.logger.impl.DefaultLogEventCreator.java

@Override
public LogEvent createLogEvent(MuleEvent muleEvent, LogLevelType logLevel, String logMessage, String loggerName,
        String argIntegrationScenario, // TODO integrationScenario, 
        String argContractId, // TODO contractId,
        String correlationId, Map<String, String> extraInfo, Throwable exception, Object payload) {

    // --------------------------
    ///*www . ja v  a2s .c o  m*/
    // 1. Process input variables
    //
    // --------------------------

    MuleMessage message = muleEvent.getMessage();

    // TODO: Will event-context always be null when an error is reported?
    // If so then its probably better to move this code to the info-logger method.
    String serviceImplementation = "";
    MuleEventContext event = RequestContext.getEventContext();
    if (event != null) {
        serviceImplementation = MuleUtil.getServiceName(event);
    }

    String endpoint = getEndpoint(message, event);

    String messageId = "";
    String integrationScenarioId = "";
    String contractId = "";
    String businessCorrelationId = correlationId;
    String propertyBusinessContextId = null;

    if (message != null) {

        if (log.isDebugEnabled()) {
            @SuppressWarnings("rawtypes")
            Set names = message.getPropertyNames(PropertyScope.INBOUND);
            for (Object object : names) {
                Object value = message.getInboundProperty(object.toString());
                log.debug(object + " = " + value + " (" + object.getClass().getName() + ")");
            }
        }

        messageId = message.getUniqueId();
        contractId = message.getInboundProperty(SOITOOLKIT_CONTRACT_ID, "");
        businessCorrelationId = message.getSessionProperty(SOITOOLKIT_CORRELATION_ID, "");
        integrationScenarioId = message.getInboundProperty(SOITOOLKIT_INTEGRATION_SCENARIO, "");
        propertyBusinessContextId = message.getInboundProperty(SOITOOLKIT_BUSINESS_CONTEXT_ID, null);

        // Override contract id from the message properties with the supplied one from the log-call, if any
        if (argContractId != null && argContractId.length() > 0) {
            contractId = argContractId;
        }

        // Override contract id from the message properties with the supplied one from the log-call, if any
        if (argIntegrationScenario != null && argIntegrationScenario.length() > 0) {
            integrationScenarioId = argIntegrationScenario;
        }
    }

    String componentId = getServerId(muleEvent);
    String payloadASstring = getPayloadAsString(payload);

    // -------------------------
    //
    // 2. Create LogEvent object
    //
    // -------------------------

    // Setup basic runtime information for the log entry
    LogRuntimeInfoType lri = new LogRuntimeInfoType();
    lri.setTimestamp(XmlUtil.convertDateToXmlDate(null));
    lri.setHostName(HOST_NAME);
    lri.setHostIp(HOST_IP);
    lri.setProcessId(PROCESS_ID);
    lri.setThreadId(Thread.currentThread().getName());
    lri.setComponentId(componentId);
    lri.setMessageId(messageId);
    lri.setBusinessCorrelationId(businessCorrelationId);

    //      // Add any business contexts
    //      if (businessContextId != null) {
    //         Set<Entry<String, String>> entries = businessContextId.entrySet();
    //         for (Entry<String, String> entry : entries) {
    //            BusinessContextId bxid = new BusinessContextId();
    //            bxid.setName(entry.getKey());
    //            bxid.setValue(entry.getValue());
    //            lri.getBusinessContextId().add(bxid);
    //         }
    //      }

    // Also add any business contexts from message properties
    if (propertyBusinessContextId != null) {
        String[] propertyArr = propertyBusinessContextId.split(",");

        for (String property : propertyArr) {
            String[] nameValueArr = property.split("=");
            String name = nameValueArr[0];
            String value = (nameValueArr.length > 1) ? nameValueArr[1] : "";
            BusinessContextId bxid = new BusinessContextId();
            bxid.setName(name);
            bxid.setValue(value);
            lri.getBusinessContextId().add(bxid);
        }

    }

    // Setup basic metadata information for the log entry
    LogMetadataInfoType lmi = new LogMetadataInfoType();
    lmi.setLoggerName(loggerName);
    lmi.setIntegrationScenarioId(integrationScenarioId);
    lmi.setContractId(contractId);
    lmi.setServiceImplementation(serviceImplementation);
    lmi.setEndpoint(endpoint);

    // Setup basic information of the log message for the log entry
    LogMessageType lm = new LogMessageType();
    lm.setLevel(logLevel);
    lm.setMessage(logMessage);

    // Setup exception information if present
    if (exception != null) {

        exception = (DefaultMuleConfiguration.verboseExceptions) ? exception
                : ExceptionHelper.summarise(exception, 5);

        LogMessageExceptionType lme = new LogMessageExceptionType();

        lme.setExceptionClass(exception.getClass().getName());
        lme.setExceptionMessage(exception.getMessage());
        StackTraceElement[] stArr = exception.getStackTrace();
        List<String> stList = new ArrayList<String>();
        for (int i = 0; i < stArr.length; i++) {
            stList.add(stArr[i].toString());
        }

        if (exception.getCause() != null) {
            Throwable ce = exception.getCause();
            ce = (DefaultMuleConfiguration.verboseExceptions) ? ce : ExceptionHelper.summarise(ce, 5);
            stList.add(CAUSE_EXCEPTION_HEADER + ": " + ce.getMessage());
            StackTraceElement[] ceStArr = ce.getStackTrace();
            for (int i = 0; i < ceStArr.length; i++) {
                stList.add(ceStArr[i].toString());
            }
        }

        if (!DefaultMuleConfiguration.verboseExceptions) {
            stList.add(
                    "*** set debug level logging or '-Dmule.verbose.exceptions=true' for full stacktrace ***");
        }
        lme.getStackTrace().addAll(stList);

        //         if (exception instanceof MuleException) {
        //               MuleException de = (MuleException)exception;
        //               System.err.println("Cause: " + de.getCause());
        //               StackTraceElement[] st = de.getCause().getStackTrace();
        //               for (int i = 0; i < st.length; i++) {
        ////                  stList.add(st[i].toString());
        //                  System.err.println(st[i].toString());
        //               }
        ////               System.err.println("Detailed: " + de.getDetailedMessage());
        ////               System.err.println("Summary: " + de.getSummaryMessage());
        ////               System.err.println("Verbose: " + de.getVerboseMessage());
        //            }

        lm.setException(lme);
    }

    // Create the log entry object
    LogEntryType logEntry = new LogEntryType();
    logEntry.setMetadataInfo(lmi);
    logEntry.setRuntimeInfo(lri);
    logEntry.setMessageInfo(lm);
    logEntry.setPayload(payloadASstring);

    // Add any extra info
    if (extraInfo != null) {
        Set<Entry<String, String>> entries = extraInfo.entrySet();
        for (Entry<String, String> entry : entries) {
            ExtraInfo ei = new ExtraInfo();
            ei.setName(entry.getKey());
            ei.setValue(entry.getValue());
            logEntry.getExtraInfo().add(ei);
        }
    }

    // Create the final log event object
    LogEvent logEvent = new LogEvent();
    logEvent.setLogEntry(logEntry);

    // We are actually done :-)
    return logEvent;
}

From source file:org.regenstrief.util.Util.java

public final static String getAbbreviatedStackTraceString(Throwable e) {
    /*//from w  w w .ja  v a2  s  .com
    Abbreviates package names and removes unnecessary content.
    Doesn't remove lines from the stack or causes.
    */
    final StringBuilder trace = new StringBuilder();
    final char br = '\n';
    StackTraceElement[] causedElems = null;
    while (e != null) {
        if (trace.length() > 0) {
            trace.append(br).append("By: ");
        }
        trace.append(replaceAllExact(abbreviateClass(e.toString()), "NullPointerException", "NPE"));
        final StackTraceElement[] elems = e.getStackTrace();
        int m = elems.length - 1, n = (causedElems == null) ? -1 : (causedElems.length - 1);
        while ((m >= 0) && (n >= 0) && elems[m].equals(causedElems[n])) {
            m--;
            n--;
        }
        for (int i = 0; i <= m; i++) {
            appendSeparator(trace, br).append(abbreviateClass(elems[i].toString()));
        }
        e = e.getCause();
        causedElems = elems;
    }
    return trace.toString();
}