Example usage for java.lang StackTraceElement StackTraceElement

List of usage examples for java.lang StackTraceElement StackTraceElement

Introduction

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

Prototype

public StackTraceElement(String declaringClass, String methodName, String fileName, int lineNumber) 

Source Link

Document

Creates a stack trace element representing the specified execution point.

Usage

From source file:de.vandermeer.skb.base.message.Message5WH_Tests.java

@Test
public void testBuilderMethods() {
    //test the set/add methods that return a message object, aka builder methods
    //this test only checks if the set/add methods returns a message object with that set/add being done correctly for valid values
    Message5WH m;//from ww  w .  j a v a2  s  .c o m

    m = new Message5WH().setReporter("repTest");
    assertEquals("repTest", m.getReporter());

    m = new Message5WH().setType(EMessageType.ERROR);
    assertTrue(m.getType() == EMessageType.ERROR);

    m = new Message5WH().setWho("whoTest");
    assertEquals("whoTest", m.getWho());

    m = new Message5WH().setWhen("whenTest");
    assertEquals("whenTest", m.getWhen());

    //SkbMessage setWhere(Object, int, int)
    m = new Message5WH().setWhere("whereTest", 10, 20);
    this.testWhereST(m.getWhere(), "whereTest", "10", "20");

    //SkbMessage setWhere(Object, RecognitionException)
    //      RecognitionException re=new RecognitionException();
    //      re.line=10;
    //      re.charPositionInLine=20;
    //      m=new Message5WH().setWhere("whereRE", re);
    //      this.testWhereST(m.getWhere(), "whereRE", "10", "20");

    //SkbMessage setWhere(Object, Token)
    CommonToken tk = new CommonToken(0);
    tk.setLine(10);
    tk.setCharPositionInLine(20);
    m = new Message5WH().setWhere("whereToken", tk);
    this.testWhereST(m.getWhere(), "whereToken", "10", "20");

    //SkbMessage setWhere(Object, Tree)
    //      Tree tree=new CommonTree(tk);
    //      m=new Message5WH().setWhere("whereTree", tree);
    //      this.testWhereST(m.getWhere(), "whereTree", "10", "20");

    //SkbMessage setWhere(StackTraceElement)
    StackTraceElement ste = new StackTraceElement("myClass", "myMethod", "myFilename", 10);
    m = new Message5WH().setWhere(ste);
    this.testWhereST(m.getWhere(), Arrays.asList(new Object[] { "myClass", "myMethod" }), "10", null);

    //for what, how and why we do a .toString() equals only, exact equals tested elsewhere
    m = new Message5WH().addWhat("whatTest");
    assertEquals("whatTest", m.getWhat().toString());

    m = new Message5WH().addHow("howTest");
    assertEquals("howTest", m.getHow().toString());

    m = new Message5WH().addWhy("whyTest");
    assertEquals("whyTest", m.getWhy().toString());
}

From source file:hudson.FunctionsTest.java

@Issue("JDK-6507809")
@Test//  ww  w.j  a  va 2  s . c  o  m
public void printThrowable() throws Exception {
    // Basics: a single exception. No change.
    assertPrintThrowable(new Stack("java.lang.NullPointerException: oops", "p.C.method1:17", "m.Main.main:1"),
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method1(C.java:17)\n"
                    + "\tat m.Main.main(Main.java:1)\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method1(C.java:17)\n"
                    + "\tat m.Main.main(Main.java:1)\n");
    // try {} catch (Exception x) {throw new IllegalStateException(x);}
    assertPrintThrowable(
            new Stack("java.lang.IllegalStateException: java.lang.NullPointerException: oops", "p.C.method1:19",
                    "m.Main.main:1")
                            .cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23",
                                    "p.C.method1:17", "m.Main.main:1")),
            "java.lang.IllegalStateException: java.lang.NullPointerException: oops\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n"
                    + "Caused by: java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "\t... 1 more\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "Caused: java.lang.IllegalStateException\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n");
    // try {} catch (Exception x) {throw new IllegalStateException("more info");}
    assertPrintThrowable(
            new Stack("java.lang.IllegalStateException: more info", "p.C.method1:19", "m.Main.main:1")
                    .cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23", "p.C.method1:17",
                            "m.Main.main:1")),
            "java.lang.IllegalStateException: more info\n" + "\tat p.C.method1(C.java:19)\n"
                    + "\tat m.Main.main(Main.java:1)\n" + "Caused by: java.lang.NullPointerException: oops\n"
                    + "\tat p.C.method2(C.java:23)\n" + "\tat p.C.method1(C.java:17)\n" + "\t... 1 more\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "Caused: java.lang.IllegalStateException: more info\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n");
    // try {} catch (Exception x) {throw new IllegalStateException("more info: " + x);}
    assertPrintThrowable(
            new Stack("java.lang.IllegalStateException: more info: java.lang.NullPointerException: oops",
                    "p.C.method1:19", "m.Main.main:1")
                            .cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23",
                                    "p.C.method1:17", "m.Main.main:1")),
            "java.lang.IllegalStateException: more info: java.lang.NullPointerException: oops\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n"
                    + "Caused by: java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "\t... 1 more\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "Caused: java.lang.IllegalStateException: more info\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n");
    // Synthetic stack showing an exception made elsewhere, such as happens with hudson.remoting.Channel.attachCallSiteStackTrace.
    Throwable t = new Stack("remote.Exception: oops", "remote.Place.method:17", "remote.Service.run:9");
    StackTraceElement[] callSite = new Stack("wrapped.Exception", "local.Side.call:11", "local.Main.main:1")
            .getStackTrace();
    StackTraceElement[] original = t.getStackTrace();
    StackTraceElement[] combined = new StackTraceElement[original.length + 1 + callSite.length];
    System.arraycopy(original, 0, combined, 0, original.length);
    combined[original.length] = new StackTraceElement(".....", "remote call", null, -2);
    System.arraycopy(callSite, 0, combined, original.length + 1, callSite.length);
    t.setStackTrace(combined);
    assertPrintThrowable(t,
            "remote.Exception: oops\n" + "\tat remote.Place.method(Place.java:17)\n"
                    + "\tat remote.Service.run(Service.java:9)\n" + "\tat ......remote call(Native Method)\n"
                    + "\tat local.Side.call(Side.java:11)\n" + "\tat local.Main.main(Main.java:1)\n",
            "remote.Exception: oops\n" + "\tat remote.Place.method(Place.java:17)\n"
                    + "\tat remote.Service.run(Service.java:9)\n" + "\tat ......remote call(Native Method)\n"
                    + "\tat local.Side.call(Side.java:11)\n" + "\tat local.Main.main(Main.java:1)\n");
    // Same but now using a cause on the remote side.
    t = new Stack("remote.Wrapper: remote.Exception: oops", "remote.Place.method2:19", "remote.Service.run:9")
            .cause(new Stack("remote.Exception: oops", "remote.Place.method1:11", "remote.Place.method2:17",
                    "remote.Service.run:9"));
    callSite = new Stack("wrapped.Exception", "local.Side.call:11", "local.Main.main:1").getStackTrace();
    original = t.getStackTrace();
    combined = new StackTraceElement[original.length + 1 + callSite.length];
    System.arraycopy(original, 0, combined, 0, original.length);
    combined[original.length] = new StackTraceElement(".....", "remote call", null, -2);
    System.arraycopy(callSite, 0, combined, original.length + 1, callSite.length);
    t.setStackTrace(combined);
    assertPrintThrowable(t,
            "remote.Wrapper: remote.Exception: oops\n" + "\tat remote.Place.method2(Place.java:19)\n"
                    + "\tat remote.Service.run(Service.java:9)\n" + "\tat ......remote call(Native Method)\n"
                    + "\tat local.Side.call(Side.java:11)\n" + "\tat local.Main.main(Main.java:1)\n"
                    + "Caused by: remote.Exception: oops\n" + "\tat remote.Place.method1(Place.java:11)\n"
                    + "\tat remote.Place.method2(Place.java:17)\n"
                    + "\tat remote.Service.run(Service.java:9)\n",
            "remote.Exception: oops\n" + "\tat remote.Place.method1(Place.java:11)\n"
                    + "\tat remote.Place.method2(Place.java:17)\n" + "\tat remote.Service.run(Service.java:9)\n"
                    + // we do not know how to elide the common part in this case
                    "Caused: remote.Wrapper\n" + "\tat remote.Place.method2(Place.java:19)\n"
                    + "\tat remote.Service.run(Service.java:9)\n" + "\tat ......remote call(Native Method)\n"
                    + "\tat local.Side.call(Side.java:11)\n" + "\tat local.Main.main(Main.java:1)\n");
    // Suppressed exceptions:
    assertPrintThrowable(
            new Stack("java.lang.IllegalStateException: java.lang.NullPointerException: oops", "p.C.method1:19",
                    "m.Main.main:1")
                            .cause(new Stack("java.lang.NullPointerException: oops", "p.C.method2:23",
                                    "p.C.method1:17", "m.Main.main:1"))
                            .suppressed(
                                    new Stack("java.io.IOException: could not close", "p.C.close:99",
                                            "p.C.method1:18", "m.Main.main:1"),
                                    new Stack("java.io.IOException: java.lang.NullPointerException",
                                            "p.C.flush:77", "p.C.method1:18", "m.Main.main:1")
                                                    .cause(new Stack("java.lang.NullPointerException",
                                                            "p.C.findFlushee:70", "p.C.flush:75",
                                                            "p.C.method1:18", "m.Main.main:1"))),
            "java.lang.IllegalStateException: java.lang.NullPointerException: oops\n"
                    + "\tat p.C.method1(C.java:19)\n" + "\tat m.Main.main(Main.java:1)\n"
                    + "\tSuppressed: java.io.IOException: could not close\n" + "\t\tat p.C.close(C.java:99)\n"
                    + "\t\tat p.C.method1(C.java:18)\n" + "\t\t... 1 more\n"
                    + "\tSuppressed: java.io.IOException: java.lang.NullPointerException\n"
                    + "\t\tat p.C.flush(C.java:77)\n" + "\t\tat p.C.method1(C.java:18)\n" + "\t\t... 1 more\n"
                    + "\tCaused by: java.lang.NullPointerException\n" + "\t\tat p.C.findFlushee(C.java:70)\n"
                    + "\t\tat p.C.flush(C.java:75)\n" + "\t\t... 2 more\n"
                    + "Caused by: java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "\t... 1 more\n",
            "java.lang.NullPointerException: oops\n" + "\tat p.C.method2(C.java:23)\n"
                    + "\tat p.C.method1(C.java:17)\n" + "Also:   java.io.IOException: could not close\n"
                    + "\t\tat p.C.close(C.java:99)\n" + "\t\tat p.C.method1(C.java:18)\n"
                    + "Also:   java.lang.NullPointerException\n" + "\t\tat p.C.findFlushee(C.java:70)\n"
                    + "\t\tat p.C.flush(C.java:75)\n" + "\tCaused: java.io.IOException\n"
                    + "\t\tat p.C.flush(C.java:77)\n" + "\t\tat p.C.method1(C.java:18)\n"
                    + "Caused: java.lang.IllegalStateException\n" + "\tat p.C.method1(C.java:19)\n"
                    + "\tat m.Main.main(Main.java:1)\n");
    // Custom printStackTrace implementations:
    assertPrintThrowable(new Throwable() {
        @Override
        public void printStackTrace(PrintWriter s) {
            s.println("Some custom exception");
        }
    }, "Some custom exception\n", "Some custom exception\n");
    // Circular references:
    Stack stack1 = new Stack("p.Exc1", "p.C.method1:17");
    Stack stack2 = new Stack("p.Exc2", "p.C.method2:27");
    stack1.cause(stack2);
    stack2.cause(stack1);
    assertPrintThrowable(stack1,
            "p.Exc1\n" + "\tat p.C.method1(C.java:17)\n" + "Caused by: p.Exc2\n"
                    + "\tat p.C.method2(C.java:27)\n" + "\t[CIRCULAR REFERENCE:p.Exc1]\n",
            "<cycle to p.Exc1>\n" + "Caused: p.Exc2\n" + "\tat p.C.method2(C.java:27)\n" + "Caused: p.Exc1\n"
                    + "\tat p.C.method1(C.java:17)\n");
}

From source file:org.lilyproject.avro.AvroConverter.java

private Throwable restoreCauses(List<AvroExceptionCause> remoteCauses) {
    Throwable result = null;/*from   ww  w.  jav a2 s  .c om*/

    for (AvroExceptionCause remoteCause : remoteCauses) {
        List<StackTraceElement> stackTrace = new ArrayList<StackTraceElement>(
                remoteCause.getStackTrace().size());

        for (AvroStackTraceElement el : remoteCause.getStackTrace()) {
            stackTrace.add(new StackTraceElement(el.getClassName(), el.getMethodName(), el.getFileName(),
                    el.getLineNumber()));
        }

        RestoredException cause = new RestoredException(remoteCause.getMessage(), remoteCause.getClassName(),
                stackTrace);

        if (result == null) {
            result = cause;
        } else {
            result.initCause(cause);
            result = cause;
        }
    }

    return result;
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Log the error that occurred and provide an exception that encapsulates the failure as best as
 * possible. This means parsing the output and if its from RTC extract the stack trace from 
 * there.//from   w  w  w. j a v a2 s .co m
 * @param fullURI The URI requested
 * @param httpResponse The response from the request
 * @param message A message for the failure if nothing can be detected from the response
 * @return An exception representing the failure
 */
@SuppressWarnings("rawtypes")
private static IOException logError(String fullURI, CloseableHttpResponse httpResponse, String message) {
    printMessageHeaders(httpResponse);

    IOException error = new IOException(message);
    try {
        InputStreamReader inputStream = new InputStreamReader(httpResponse.getEntity().getContent(), UTF_8);
        try {
            String response = IOUtils.toString(inputStream);
            // this is one lonnnng string if its a stack trace.
            // try to get it as JSON so we can output it in a more friendly way.
            try {
                JSON json = JSONSerializer.toJSON(response);
                response = json.toString(4);
                if (json instanceof JSONObject) {
                    // see if we have a stack trace
                    JSONObject jsonObject = (JSONObject) json;
                    String errorMessage = jsonObject.getString("errorMessage"); //$NON-NLS-1$
                    error = new IOException(errorMessage);
                    JSONArray trace = jsonObject.getJSONArray("errorTraceMarshall"); //$NON-NLS-1$
                    List<StackTraceElement> stackElements = new ArrayList<StackTraceElement>(trace.size());
                    for (Iterator iterator = trace.iterator(); iterator.hasNext();) {
                        Object element = iterator.next();
                        if (element instanceof JSONObject) {
                            JSONObject jsonElement = (JSONObject) element;
                            String cls = jsonElement.getString("errorTraceClassName"); //$NON-NLS-1$
                            String method = jsonElement.getString("errorTraceMethodName"); //$NON-NLS-1$
                            String file = jsonElement.getString("errorTraceFileName"); //$NON-NLS-1$
                            int line = jsonElement.getInt("errorTraceLineNumber"); //$NON-NLS-1$
                            StackTraceElement stackElement = new StackTraceElement(cls, method, file, line);
                            stackElements.add(stackElement);
                        }
                    }
                    error.setStackTrace(stackElements.toArray(new StackTraceElement[stackElements.size()]));

                    // our RTC responses have the stack trace in there twice. Remove 1 copy of it.
                    jsonObject.remove("errorTraceMarshall"); //$NON-NLS-1$
                    response = jsonObject.toString(4);
                }
            } catch (JSONException e) {
                // not JSON or not a RTC stack trace in the JSONObject so just log what we have
            }
            LOGGER.finer(response);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOGGER.finer("Failed to close the result input stream for request: " + fullURI); //$NON-NLS-1$
            }
        }
    } catch (IOException e) {
        LOGGER.finer("Unable to capture details of the failure"); //$NON-NLS-1$
    }
    return error;
}

From source file:org.nanocom.console.Application.java

/**
 * Renders a caught exception./* w  ww.  j a  v a  2 s. c o m*/
 *
 * @param e      An exception instance
 * @param output An OutputInterface instance
 */
public void renderException(Exception e, OutputInterface output) {
    Throwable t = e;
    do {
        String title = String.format("  [%s]  ", t.getClass().getSimpleName());
        int len = title.length();
        Integer width = getTerminalWidth();

        if (null == width) {
            width = Integer.MAX_VALUE;
        } else {
            width--;
        }

        List<String> lines = new ArrayList<String>();
        String[] splittedMessage = t.getMessage().split("\r?\n");

        for (String line : splittedMessage) {
            String[] lines2 = split(line, width - 4);
            for (String line2 : lines2) {
                lines.add(String.format("  %s  ", line2));
                len = Math.max(line2.length() + 4, len);
            }
        }

        List<String> messages = new ArrayList<String>();
        messages.add(repeat(" ", len));
        messages.add(title + repeat(" ", Math.max(0, len - title.length())));

        for (String line : lines) {
            messages.add(line + repeat(" ", len - line.length()));
        }

        messages.add(repeat(" ", len));

        output.writeln(EMPTY);
        output.writeln(EMPTY);

        for (String message : messages) {
            output.writeln(String.format("<error>%s</error>", message));
        }

        output.writeln(EMPTY);
        output.writeln(EMPTY);

        if (OutputInterface.VerbosityLevel.VERBOSE.equals(output.getVerbosity())) {
            output.writeln("<comment>Exception trace:</comment>");

            // exception related properties
            StackTraceElement[] trace = t.getStackTrace();
            StackTraceElement[] fullTrace = ArrayUtils
                    .addAll(new StackTraceElement[] { new StackTraceElement(EMPTY, trace[0].getMethodName(),
                            trace[0].getFileName(), trace[0].getLineNumber()) }, trace);

            int count = fullTrace.length;
            int i;
            for (i = 0; i < count; i++) {
                String clazz = null != fullTrace[i].getClassName() ? fullTrace[i].getClassName() : EMPTY;
                String function = fullTrace[i].getMethodName();
                String file = null != fullTrace[i].getFileName() ? fullTrace[i].getFileName() : "n/a";
                String line = String.valueOf(fullTrace[i].getLineNumber());

                output.writeln(String.format(" %s%s() at <info>%s:%s</info>", clazz, function, file, line));
            }

            output.writeln(EMPTY);
            output.writeln(EMPTY);
        }
    } while (null != (t = t.getCause()));

    if (null != runningCommand) {
        output.writeln(
                String.format("<info>%s</info>", String.format(runningCommand.getSynopsis(), getName())));
        output.writeln(EMPTY);
        output.writeln(EMPTY);
    }
}

From source file:org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.Launcher.java

/**
 * //from  w  w  w  .jav  a2 s.c  om
 * @param line the string representation of a stack trace returned by {@link Throwable#printStackTrace() printStackTrace}
 * @return the StackTraceElement object representing the stack trace
 * @throws Exception
 */
public StackTraceElement getStackTraceElement(String line) throws Exception {
    /*       
     * the format of the line is something like:
     *                at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapOnly$Map.map(PigMapOnly.java:65)
     * note the white space before the 'at'. Its not of much importance but noted for posterity.    
     */
    String[] items;

    /*
     * regex for matching the fully qualified method Name
     * note the use of the $ for matching nested classes
     * and the use of < and > for constructors
     */
    String qualifiedMethodNameRegex = "(\\w+(\\$\\w+)?\\.)+(<)?\\w+(>)?";
    Pattern qualifiedMethodNamePattern = Pattern.compile(qualifiedMethodNameRegex);
    Matcher contentMatcher = qualifiedMethodNamePattern.matcher(line);

    //org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapOnly$Map.map(PigMapOnly.java:65)
    String content = null;
    if (contentMatcher.find()) {
        content = line.substring(contentMatcher.start());
    } else {
        int errCode = 2057;
        String msg = "Did not find fully qualified method name to reconstruct stack trace: " + line;
        throw new ExecException(msg, errCode, PigException.BUG);
    }

    Matcher qualifiedMethodNameMatcher = qualifiedMethodNamePattern.matcher(content);

    //org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapOnly$Map.map
    String qualifiedMethodName = null;
    //(PigMapOnly.java:65)
    String fileDetails = null;

    if (qualifiedMethodNameMatcher.find()) {
        qualifiedMethodName = qualifiedMethodNameMatcher.group();
        fileDetails = content.substring(qualifiedMethodNameMatcher.end() + 1);
    } else {
        int errCode = 2057;
        String msg = "Did not find fully qualified method name to reconstruct stack trace: " + line;
        throw new ExecException(msg, errCode, PigException.BUG);
    }

    //From the fully qualified method name, extract the declaring class and method name
    items = qualifiedMethodName.split("\\.");

    //initialize the declaringClass (to org in most cases)
    String declaringClass = items[0];
    //the last member is always the method name
    String methodName = items[items.length - 1];
    StringBuilder sb = new StringBuilder();

    //concatenate the names by adding the dot (.) between the members till the penultimate member
    for (int i = 1; i < items.length - 1; ++i) {
        sb.append('.');
        sb.append(items[i]);
    }

    declaringClass += sb.toString();

    //from the file details extract the file name and the line number
    //PigMapOnly.java:65
    fileDetails = fileDetails.substring(0, fileDetails.length() - 1);
    items = fileDetails.split(":");
    //PigMapOnly.java
    String fileName = null;
    int lineNumber = -1;
    if (items.length > 0) {
        fileName = items[0];
        if (items.length > 1) {
            lineNumber = Integer.parseInt(items[1]);
        }
    }
    return new StackTraceElement(declaringClass, methodName, fileName, lineNumber);
}

From source file:org.apache.pig.backend.hadoop.executionengine.Launcher.java

/**
 *
 * @param line//w w w  .j  a v  a  2s.co  m
 *            the string representation of a stack trace returned by
 *            {@link Throwable#printStackTrace() printStackTrace}
 * @return the StackTraceElement object representing the stack trace
 * @throws Exception
 */
public StackTraceElement getStackTraceElement(String line) throws Exception {
    /*
     * the format of the line is something like: at
     * org.apache.pig.backend.hadoop
     * .executionengine.mapReduceLayer.PigMapOnly$Map
     * .map(PigMapOnly.java:65) note the white space before the 'at'. Its
     * not of much importance but noted for posterity.
     */
    String[] items;

    /*
     * regex for matching the fully qualified method Name note the use of
     * the $ for matching nested classes and the use of < and > for
     * constructors
     */
    String qualifiedMethodNameRegex = "(\\w+(\\$\\w+)?\\.)+(<)?\\w+(>)?";
    Pattern qualifiedMethodNamePattern = Pattern.compile(qualifiedMethodNameRegex);
    Matcher contentMatcher = qualifiedMethodNamePattern.matcher(line);

    // org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapOnly$Map.map(PigMapOnly.java:65)
    String content = null;
    if (contentMatcher.find()) {
        content = line.substring(contentMatcher.start());
    } else {
        int errCode = 2057;
        String msg = "Did not find fully qualified method name to reconstruct stack trace: " + line;
        throw new ExecException(msg, errCode, PigException.BUG);
    }

    Matcher qualifiedMethodNameMatcher = qualifiedMethodNamePattern.matcher(content);

    // org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigMapOnly$Map.map
    String qualifiedMethodName = null;
    // (PigMapOnly.java:65)
    String fileDetails = null;

    if (qualifiedMethodNameMatcher.find()) {
        qualifiedMethodName = qualifiedMethodNameMatcher.group();
        fileDetails = content.substring(qualifiedMethodNameMatcher.end() + 1);
    } else {
        int errCode = 2057;
        String msg = "Did not find fully qualified method name to reconstruct stack trace: " + line;
        throw new ExecException(msg, errCode, PigException.BUG);
    }

    // From the fully qualified method name, extract the declaring class and
    // method name
    items = qualifiedMethodName.split("\\.");

    // initialize the declaringClass (to org in most cases)
    String declaringClass = items[0];
    // the last member is always the method name
    String methodName = items[items.length - 1];
    StringBuilder sb = new StringBuilder();

    // concatenate the names by adding the dot (.) between the members till
    // the penultimate member
    for (int i = 1; i < items.length - 1; ++i) {
        sb.append('.');
        sb.append(items[i]);
    }

    declaringClass += sb.toString();

    // from the file details extract the file name and the line number
    // PigMapOnly.java:65
    fileDetails = fileDetails.substring(0, fileDetails.length() - 1);
    items = fileDetails.split(":");
    // PigMapOnly.java
    String fileName = null;
    int lineNumber = -1;
    if (items.length > 0) {
        fileName = items[0];
        if (items.length > 1) {
            lineNumber = Integer.parseInt(items[1]);
        }
    }
    return new StackTraceElement(declaringClass, methodName, fileName, lineNumber);
}

From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java

private void dumpScriptPythonStackDetails(TestResult result, Throwable error) {
    StringBuilder stackTrace = new StringBuilder();

    // get stacktrace from PyException traceback, because easier and line number is not always correct in Java stack trace
    if (error instanceof PyException) {
        List<PyFrame> stacktrace = new ArrayList<>();
        PyTraceback previousTraceback = null;
        PyTraceback traceback = ((PyException) error).traceback;
        while (traceback != null && traceback != previousTraceback) {
            PyFrame frame = traceback.tb_frame;
            String fileName;/*ww  w  .  ja  v  a2 s  . co m*/
            String function;

            if (frame != null && frame.f_code != null && (fileName = frame.f_code.co_filename) != null
                    && (function = frame.f_code.co_name) != null) {
                // skip execfile() call in the embedded jython, doStep() and doSteps() functions,
                // private __invokexxx() methods of the __TestAPIWrapper class,
                // private __checkPresent() method of a test API wrapper class,
                // user_line() method of the __ScriptDebugger class and a function of the debugger
                if ((!fileName.equals("embedded_jython") || (!function.equals("<module>")
                        && !function.equals("doStep") && !function.equals("doSteps")
                        && !function.startsWith("_TestAPIWrapper__invoke")
                        && !function.endsWith("__checkPresent") && !function.equals("user_line")))
                        && !fileName.endsWith(File.separator + "bdb.py")) {
                    stacktrace.add(frame);
                }
            }

            previousTraceback = traceback;
            traceback = (PyTraceback) traceback.tb_next;
        }

        // extract all necessary details from stacktrace from last frame to first one
        boolean stackLastDataExtracted = false;
        ListIterator<PyFrame> frameIterator = stacktrace.listIterator(stacktrace.size());
        while (frameIterator.hasPrevious()) {
            PyFrame frame = frameIterator.previous();
            String fileName = frame.f_code.co_filename;
            String function = frame.f_code.co_name;
            int lineNumber = frame.f_lineno;

            // convert absolute path to relative path
            Path filePath = Paths.get(fileName);
            if (filePath.isAbsolute()) {
                filePath = Paths.get("").toAbsolutePath().relativize(filePath);
            }
            // normalize path
            fileName = filePath.normalize().toString();

            if (function.equals("<module>")) {
                stackTrace.append("at file ").append(fileName).append(" line ").append(lineNumber).append('\n');
            } else if (!function.equals("importTestScript")) {
                stackTrace.append("function ").append(function);
                if (!fileName.equals("embedded_jython") && !fileName.equals("JythonTestScript.java")) {
                    stackTrace.append(" at file ").append(fileName).append(" line ").append(lineNumber);
                }
                stackTrace.append('\n');
            }
            if (!stackLastDataExtracted && !fileName.equals("embedded_jython")
                    && !fileName.equals("JythonTestScript.java")) {
                stackLastDataExtracted = true;
                result.setFailedLineNumber(lineNumber);
                result.setFailedFunctionId(function);
            }
            result.addStackTraceElement(new StackTraceElement("", function, fileName, lineNumber));
        }
    }

    result.setStackTrace(stackTrace.toString().trim());
}

From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java

private void handleScriptException(ScriptException e, TestResult result) {
    Throwable cause = e.getCause();

    // handle ThreadDeath exception
    if (cause instanceof PyException) {
        PyException pe = (PyException) cause;
        if (pe.value instanceof PyObjectDerived) {
            Object javaError = pe.value.__tojava__(Throwable.class);
            if (javaError != null && javaError != Py.NoConversion) {
                if (javaError instanceof ThreadDeath) {
                    dumpScriptPythonStackDetails(result, cause);
                    throw (ThreadDeath) javaError;
                }/*w w  w. j a v  a 2s.  c  o  m*/
            }
        }
    }

    result.setFailedLineNumber(e.getLineNumber());
    result.setStatus(TestResult.Status.NOT_AVAILABLE);
    String message = null;
    boolean dumpStack = true;

    if (cause instanceof PySyntaxError) {
        // set a clear syntax error message
        PySyntaxError syntaxError = (PySyntaxError) cause;
        try {
            PyString fileName, text;
            PyInteger lineNumber, columnNumber;
            if (syntaxError.value instanceof PyTuple) {
                PyObject[] infos = ((PyTuple) ((PyTuple) syntaxError.value).getArray()[1]).getArray();
                fileName = (PyString) infos[0];
                lineNumber = (PyInteger) infos[1];
                columnNumber = (PyInteger) infos[2];
                text = (PyString) infos[3];
            } else {
                fileName = (PyString) syntaxError.value.__getattr__(new PyString("filename"));
                lineNumber = (PyInteger) syntaxError.value.__getattr__(new PyString("lineno"));
                columnNumber = (PyInteger) syntaxError.value.__getattr__(new PyString("offset"));
                text = (PyString) syntaxError.value.__getattr__(new PyString("text"));
            }
            message = "Python syntax error in file " + fileName + " at line " + lineNumber + ", column "
                    + columnNumber + ":\n" + text;
            result.addStackTraceElement(
                    new StackTraceElement("", "", fileName.toString(), lineNumber.getValue()));
            dumpStack = false;
        } catch (PyException pye) {
            message = "Python syntax error (Couldn't decode localization of error)";
        }
    } else if (cause instanceof PyException) {
        PyException pe = (PyException) cause;
        if (pe.value instanceof PyObjectDerived) {
            // check  if exception is UndeclaredThrowableException
            // in this case status is "failed" and message is taken from cause exception
            Object javaError = pe.value.__tojava__(Throwable.class);
            if (javaError != null && javaError != Py.NoConversion) {
                if (javaError instanceof QTasteException) {
                    handleQTasteException((QTasteException) javaError, result);
                    message = result.getExtraResultDetails();
                } else if (javaError instanceof UndeclaredThrowableException) {
                    result.setStatus(TestResult.Status.FAIL);
                    Throwable undeclaredThrowable = ((UndeclaredThrowableException) javaError).getCause();
                    if (undeclaredThrowable instanceof InvocationTargetException) {
                        message = getThrowableDescription(undeclaredThrowable.getCause());
                    } else {
                        message = getThrowableDescription(undeclaredThrowable);
                    }
                } else if (javaError instanceof Throwable) {
                    message = getThrowableDescription((Throwable) javaError);
                }
            }
        }
        if (message == null) {
            if (pe.type instanceof PyType) {
                String errorName = null, errorValue;
                try {
                    PyObject doc = pe.value.__getattr__(new PyString("__doc__"));
                    if (doc != Py.None) {
                        errorName = doc.toString();
                        if (errorName.endsWith(".")) {
                            errorName = errorName.substring(0, errorName.length() - 1);
                        }
                    }
                } catch (PyException pye) {
                }
                if (errorName == null) {
                    errorName = ((PyType) pe.type).getName();
                }

                try {
                    errorValue = pe.value.__str__().toString();
                } catch (PyException pye) {
                    errorValue = pe.value.toString();
                }
                if (errorValue.startsWith(errorName)) {
                    message = errorValue;
                } else {
                    message = errorName + ": " + errorValue;
                }
            } else {
                message = getThrowableDescription(e);
            }
        }
    } else {
        message = getThrowableDescription(e);
    }

    result.setExtraResultDetails(message);
    if (dumpStack) {
        dumpScriptPythonStackDetails(result, cause);
    }

    if (!result.getExtraResultDetails().isEmpty()) {
        logger.error(result.getExtraResultDetails());
    }
    if ((result.getStackTrace() != null) && !result.getStackTrace().isEmpty()) {
        logger.error("Script stack trace: \n" + result.getStackTrace());
    }
}