Example #1
0
 /**
  * Filter the stacktrace elements with only interesting one.
  *
  * @param throwable throwable
  * @return {@link Throwable} instance with interested stacktrace elements.
  */
 public static Throwable sanitize(Throwable throwable) {
   if (throwable instanceof NGrinderRuntimeException) {
     if (((NGrinderRuntimeException) throwable).isSanitized()) {
       return throwable;
     }
   }
   Throwable t = throwable;
   while (t != null) {
     // Note that this getBoolean access may well be synced...
     StackTraceElement[] trace = t.getStackTrace();
     List<StackTraceElement> newTrace = CollectionUtils.newArrayList();
     for (StackTraceElement stackTraceElement : trace) {
       if (isApplicationClass(stackTraceElement.getClassName())) {
         newTrace.add(stackTraceElement);
       }
     }
     StackTraceElement[] clean = new StackTraceElement[newTrace.size()];
     newTrace.toArray(clean);
     t.setStackTrace(clean);
     t = t.getCause();
   }
   if (throwable instanceof NGrinderRuntimeException) {
     ((NGrinderRuntimeException) throwable).setSanitized(true);
   }
   return throwable;
 }
Example #2
0
  /**
   * Gets the stack trace of the Throwable that caused this crash report, or if that fails, the
   * cause .toString().
   */
  public String getCauseStackTraceOrString() {
    StringWriter stringwriter = null;
    PrintWriter printwriter = null;
    Throwable throwable = this.cause;

    if (throwable.getMessage() == null) {
      if (throwable instanceof NullPointerException) {
        throwable = new NullPointerException(this.description);
      } else if (throwable instanceof StackOverflowError) {
        throwable = new StackOverflowError(this.description);
      } else if (throwable instanceof OutOfMemoryError) {
        throwable = new OutOfMemoryError(this.description);
      }

      throwable.setStackTrace(this.cause.getStackTrace());
    }

    String s = throwable.toString();

    try {
      stringwriter = new StringWriter();
      printwriter = new PrintWriter(stringwriter);
      throwable.printStackTrace(printwriter);
      s = stringwriter.toString();
    } finally {
      IOUtils.closeQuietly((Writer) stringwriter);
      IOUtils.closeQuietly((Writer) printwriter);
    }

    return s;
  }
Example #3
0
 Throwable cleanStackTrace(Throwable e) {
     List<StackTraceElement> cleanTrace = new ArrayList<StackTraceElement>();
     for (StackTraceElement se : e.getStackTrace()) {
         if (se.getClassName().startsWith("Template_")) {
             String tn = se.getClassName().substring(9);
             if (tn.indexOf("$") > -1) {
                 tn = tn.substring(0, tn.indexOf("$"));
             }
             Integer line = TemplateLoader.templates.get(tn).linesMatrix.get(se.getLineNumber());
             if (line != null) {
                 String ext = "";
                 if (tn.indexOf(".") > -1) {
                     ext = tn.substring(tn.indexOf(".") + 1);
                     tn = tn.substring(0, tn.indexOf("."));
                 }
                 StackTraceElement nse = new StackTraceElement(TemplateLoader.templates.get(tn).name, ext, "line", line);
                 cleanTrace.add(nse);
             }
         }
         if (!se.getClassName().startsWith("org.codehaus.groovy.") && !se.getClassName().startsWith("groovy.") && !se.getClassName().startsWith("sun.reflect.") && !se.getClassName().startsWith("java.lang.reflect.") && !se.getClassName().startsWith("Template_")) {
             cleanTrace.add(se);
         }
     }
     e.setStackTrace(cleanTrace.toArray(new StackTraceElement[cleanTrace.size()]));
     return e;
 }
    private void finishConnect() {
      // Note this method is invoked by the event loop only if the connection attempt was
      // neither cancelled nor timed out.

      assert eventLoop().inEventLoop();

      boolean connectStillInProgress = false;
      try {
        boolean wasActive = isActive();
        if (!doFinishConnect()) {
          connectStillInProgress = true;
          return;
        }
        fulfillConnectPromise(connectPromise, wasActive);
      } catch (Throwable t) {
        if (t instanceof ConnectException) {
          Throwable newT = new ConnectException(t.getMessage() + ": " + requestedRemoteAddress);
          newT.setStackTrace(t.getStackTrace());
          t = newT;
        }

        fulfillConnectPromise(connectPromise, t);
      } finally {
        if (!connectStillInProgress) {
          // Check for null as the connectTimeoutFuture is only created if a connectTimeoutMillis >
          // 0 is used
          // See https://github.com/netty/netty/issues/1770
          if (connectTimeoutFuture != null) {
            connectTimeoutFuture.cancel(false);
          }
          connectPromise = null;
        }
      }
    }
Example #5
0
 public static <T extends Throwable> T trace(String message, T t) {
   Throwable filtered = new RuntimeException(t.getMessage());
   filtered.setStackTrace(Exceptions.filterStackTraceElements(t).toArray(steArrayType));
   LOG.info(message);
   LOG.trace(message, filtered);
   return t;
 }
Example #6
0
  @Override
  public void uncaughtException(Thread thread, Throwable ex) {

    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);

    // Inject some info about android version and the device, since google can't provide them in the
    // developer console
    StackTraceElement[] trace = ex.getStackTrace();
    StackTraceElement[] trace2 = new StackTraceElement[trace.length + 3];
    System.arraycopy(trace, 0, trace2, 0, trace.length);
    trace2[trace.length + 0] =
        new StackTraceElement("Android", "MODEL", android.os.Build.MODEL, -1);
    trace2[trace.length + 1] =
        new StackTraceElement("Android", "VERSION", android.os.Build.VERSION.RELEASE, -1);
    trace2[trace.length + 2] =
        new StackTraceElement("Android", "FINGERPRINT", android.os.Build.FINGERPRINT, -1);
    ex.setStackTrace(trace2);

    ex.printStackTrace(printWriter);
    String stacktrace = result.toString();
    printWriter.close();
    Log.e(TAG, stacktrace);

    // Save the log on SD card if available
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      String sdcardPath = Environment.getExternalStorageDirectory().getPath();
      writeLog(stacktrace, sdcardPath + "/vlc_crash");
      writeLogcat(sdcardPath + "/vlc_logcat");
    }

    defaultUEH.uncaughtException(thread, ex);
  }
Example #7
0
 static <Z> void verifyUsingMatcher(@Nullable Z actualValue, Matcher<? super Z> matcher) {
   try {
     MatcherAssert.assertThat(actualValue, matcher);
   } catch (Throwable ex) {
     ex.setStackTrace(trimStackTrace(ex.getStackTrace()));
     Throwables.propagate(ex);
   }
 }
Example #8
0
 static void verifyCheck(String description, boolean assertionState) {
   try {
     MatcherAssert.assertThat(description, assertionState);
   } catch (Throwable ex) {
     ex.setStackTrace(trimStackTrace(ex.getStackTrace()));
     Throwables.propagate(ex);
   }
 }
 @Override
 public Object invoke(final Object proxy, final Method method, final Object[] args)
     throws Throwable {
   if (super.shouldHandle(method, args)) return super.handle(method, args);
   if (args != null) {
     for (final Object o : args) {
       if (o != null && !(o instanceof Serializable)) {
         throw new IllegalArgumentException(
             o
                 + " is not serializable, all remote method args must be serializable.  method:"
                 + method);
       }
     }
   }
   final RemoteMethodCall remoteMethodMsg =
       new RemoteMethodCall(
           m_endPointName, method.getName(), args, method.getParameterTypes(), m_remoteType);
   if (m_ignoreResults) {
     m_messenger.invoke(m_endPointName, remoteMethodMsg);
     return null;
   } else {
     final RemoteMethodCallResults response =
         m_messenger.invokeAndWait(m_endPointName, remoteMethodMsg);
     if (response.getException() != null) {
       if (response.getException() instanceof MessengerException) {
         final MessengerException cle = (MessengerException) response.getException();
         cle.fillInInvokerStackTrace();
       } else {
         // do not chain the exception, we want to keep whatever the original exception's class
         // was, so just add our bit to the stack trace.
         final Throwable throwable = response.getException();
         final StackTraceElement[] exceptionTrace = throwable.getStackTrace();
         final Exception ourException =
             new Exception(throwable.getMessage() + " exception in response from other system");
         final StackTraceElement[] ourTrace =
             ourException.getStackTrace(); // Thread.currentThread().getStackTrace();
         if (exceptionTrace != null && ourTrace != null) {
           final StackTraceElement[] combinedTrace =
               new StackTraceElement[(exceptionTrace.length + ourTrace.length)];
           int i = 0;
           for (int j = 0; j < exceptionTrace.length; j++) {
             combinedTrace[i] = exceptionTrace[j];
             i++;
           }
           for (int k = 0; k < ourTrace.length; k++) {
             combinedTrace[i] = ourTrace[k];
             i++;
           }
           throwable.setStackTrace(combinedTrace);
         }
       }
       throw response.getException();
     }
     return response.getRVal();
   }
 }
  public void afterInvocation(IInvokedMethod method, ITestResult result) {
    resultT = result;
    String textMsg = "Completed executing " + returnMethodName(method.getTestMethod());
    Reporter.log(textMsg, true);

    Reporter.setCurrentTestResult(result);

    if (method.isTestMethod()) {

      List<Throwable> verificationFailures = TestBase.getVerificationFailures();

      // if there are verification failures...
      if (verificationFailures.size() > 0) {

        // set the test to failed
        result.setStatus(ITestResult.FAILURE);

        // if there is an assertion failure add it to verificationFailures
        if (result.getThrowable() != null) {
          verificationFailures.add(result.getThrowable());
        }

        int size = verificationFailures.size();
        // if there's only one failure just set that
        if (size == 1) {
          result.setThrowable(verificationFailures.get(0));
        } else {
          // create a failure message with all failures and stack traces (except last failure)
          StringBuffer failureMessage =
              new StringBuffer("Multiple failures (").append(size).append("):\n\n");
          for (int i = 0; i < size - 1; i++) {
            failureMessage
                .append("Failure ")
                .append(i + 1)
                .append(" of ")
                .append(size)
                .append(":\n");
            Throwable t = verificationFailures.get(i);
            String fullStackTrace = Utils.stackTrace(t, false)[1];
            failureMessage.append(fullStackTrace).append("\n\n");
          }

          // final failure
          Throwable last = verificationFailures.get(size - 1);
          failureMessage.append("Failure ").append(size).append(" of ").append(size).append(":\n");
          failureMessage.append(last.toString());

          // set merged throwable
          Throwable merged = new Throwable(failureMessage.toString());
          merged.setStackTrace(last.getStackTrace());

          result.setThrowable(merged);
        }
      }
    }
  }
Example #11
0
    public Throwable read(ClassLoader classLoader) throws IOException {
      final Throwable causeThrowable = getCause(classLoader);
      Throwable throwable = null;
      if (serializedException != null) {
        try {
          final ExceptionReplacingObjectInputStream ois =
              new ExceptionReplacingObjectInputStream(
                  new ByteArrayInputStream(serializedException), classLoader) {
                @Override
                protected Object resolveObject(Object obj) throws IOException {
                  if (obj instanceof CausePlaceholder) {
                    return causeThrowable;
                  }
                  return super.resolveObject(obj);
                }
              };
          throwable = (Throwable) ois.readObject();
        } catch (ClassNotFoundException e) {
          // Ignore
        } catch (InvalidClassException e) {
          try {
            Constructor<?> constructor = classLoader.loadClass(type).getConstructor(String.class);
            throwable = (Throwable) constructor.newInstance(message);
            throwable.initCause(causeThrowable);
            throwable.setStackTrace(stackTrace);
          } catch (ClassNotFoundException e1) {
            // Ignore
          } catch (NoSuchMethodException e1) {
            // Ignore
          } catch (Throwable t) {
            throw UncheckedException.throwAsUncheckedException(t);
          }
        }
      }

      if (throwable == null) {
        throwable = new PlaceholderException(type, message, causeThrowable);
        throwable.setStackTrace(stackTrace);
      }

      return throwable;
    }
 private static ExecutionException addSubmissionTrace(
     StackTraceElement[] submissionTrace, ExecutionException e) {
   if (e.getCause() == null) {
     return filterTrace(e);
   }
   Throwable cause = e.getCause();
   StackTraceElement[] combined =
       filterTrace(concat(cause.getStackTrace(), submissionTrace, StackTraceElement.class));
   cause.setStackTrace(combined);
   return filterTrace(e);
 }
Example #13
0
 protected void doThrowable(final Throwable e) throws Exception {
     if (parent.launchLocation != null) {
         final ArrayList<StackTraceElement> stack = new ArrayList<StackTraceElement>(Arrays.asList(e.getStackTrace()));
         stack.addAll(Arrays.asList(parent.launchLocation));
         e.setStackTrace(stack.toArray(new StackTraceElement[stack.size()]));
     }
     postToUiThreadAndWait(new Callable<Object>() {
         public Object call() throws Exception {
             parent.onThrowable(e);
             return null;
         }
     });
 }
  /**
   * Filter the throwable, but will also filter any causes (right up the cause chain) as well if the
   * <b>filterCause</b> boolean is set to <code>true</code>.
   *
   * @param t The throwable instance to filter.
   * @param filterCause When set to <code>true</code> will also filter the cause chain as well.
   * @throws QueryExecutionException If the where clause cannot be executed.
   */
  public void filter(Throwable t, boolean filterCause) throws QueryExecutionException {

    if (filterCause) {

      Throwable c = t.getCause();

      if (c != null) {

        this.filter(c, filterCause);
      }
    }

    t.setStackTrace(this.filterStackTrace(t.getStackTrace()));
  }
  /**
   * Transforms the given throwable and its recursively referenced throwables into a new exception
   * hierarchy. Exceptions that are most likely not known by an external calling party are replaced
   * by a {@link PlaceholderException} object:
   *
   * <ul>
   *   <li>{@link ProcessingException} are mapped to itself if possible, otherwise to a {@link
   *       ProcessingException}
   *   <li>Exceptions in package <code>java.*</code> are mapped to itself if possible, otherwise to
   *       a {@link PlaceholderException}
   *   <li>All other exceptions are transformed to {@link PlaceholderException}
   * </ul>
   *
   * @param t
   * @return
   */
  public static Throwable transformException(Throwable t) {
    // first, go to exception stack and reverse it
    ArrayList<Throwable> throwableStack = new ArrayList<Throwable>();
    while (t != null) {
      throwableStack.add(0, t);
      t = t.getCause();
    }

    // second, transform each exception so that they do not use probably
    // proprietary exception classes
    Throwable cause = null;
    for (Throwable throwable : throwableStack) {
      Throwable transformedThrowable = null;

      if (throwable instanceof ProcessingException) {
        ProcessingException pe = null;
        IProcessingStatus oldStatus = ((ProcessingException) throwable).getStatus();
        ProcessingStatus newStatus =
            (oldStatus instanceof ProcessingStatus
                ? (ProcessingStatus) oldStatus
                : new ProcessingStatus(oldStatus));
        newStatus.setException(cause);
        try {
          pe = (ProcessingException) transformWellKnownException(throwable, cause, newStatus);
        } catch (RuntimeException fatal) {
          // nop
        }
        if (pe == null) {
          pe = new ProcessingException();
        }
        transformedThrowable = pe.withStatus(newStatus);
      } else if (throwable.getClass().getPackage() != null
          && throwable.getClass().getPackage().getName().startsWith("java.")) {
        transformedThrowable = transformWellKnownException(throwable, cause, null);
      }

      if (transformedThrowable == null) {
        transformedThrowable = new PlaceholderException(throwable, cause);
      }

      transformedThrowable.setStackTrace(throwable.getStackTrace());
      cause = transformedThrowable;
    }
    return cause;
  }
  public static void fixStackTrace(Throwable cause, StackTraceElement[] clientSideStackTrace) {
    notNull(cause, "cause");
    notNull(clientSideStackTrace, "clientSideStackTrace");

    StackTraceElement[] serverSideStackTrace = cause.getStackTrace();
    StackTraceElement[] newStackTrace =
        new StackTraceElement[clientSideStackTrace.length + serverSideStackTrace.length];
    System.arraycopy(serverSideStackTrace, 0, newStackTrace, 0, serverSideStackTrace.length);
    newStackTrace[serverSideStackTrace.length] =
        new StackTraceElement(EXCEPTION_SEPARATOR, "", null, -1);
    System.arraycopy(
        clientSideStackTrace,
        1,
        newStackTrace,
        serverSideStackTrace.length + 1,
        clientSideStackTrace.length - 1);
    cause.setStackTrace(newStackTrace);
  }
Example #17
0
 // recursively parse the causes and instantiate corresponding throwables
 private Throwable getCause(Iterator<String> linesIterator, String firstLine) {
   // The actual exception class of the cause might be unavailable at the
   // client -> use a standard throwable to represent the cause.
   Throwable res = new Throwable(firstLine.substring(firstLine.indexOf(":") + 2));
   List<StackTraceElement> stackTraceList = new ArrayList<StackTraceElement>();
   while (linesIterator.hasNext()) {
     String oneLine = linesIterator.next();
     if (oneLine.startsWith("Caused by:")) {
       Throwable nestedCause = getCause(linesIterator, oneLine);
       res.initCause(nestedCause);
       break;
     }
     stackTraceList.add(parseStackTrackLine(oneLine));
   }
   StackTraceElement[] stackTraceElement = new StackTraceElement[stackTraceList.size()];
   res.setStackTrace(stackTraceList.toArray(stackTraceElement));
   return res;
 }
 public void cancel(Throwable cause) {
   if (state == State.CREATED) {
     assert heirs.size() == 0;
     state = State.CLOSED;
     parent.remove(this);
     return;
   }
   if (failure == null) {
     canceled = true;
     failure = new CancellationException();
     if (stackTrace != null) {
       failure.setStackTrace(stackTrace.getStackTrace());
     }
     failure.initCause(cause);
     if (state == State.TRYING) {
       cancelHeirs();
     }
   }
 }
 private static Throwable makeLanguageStackTrace(
     @NotNull Throwable currentThrowable, @NotNull PsiFile file) {
   Throwable langThrowable = new Throwable();
   FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(file);
   if (builder == null) return currentThrowable;
   Class builderClass = builder.getClass();
   Class declaringClass = builderClass.getDeclaringClass();
   String guessedFileName =
       (declaringClass == null ? builderClass.getSimpleName() : declaringClass.getSimpleName())
           + ".java";
   StackTraceElement ste =
       new StackTraceElement(builder.getClass().getName(), "createModel", guessedFileName, 1);
   StackTraceElement[] originalStackTrace = currentThrowable.getStackTrace();
   StackTraceElement[] modifiedStackTrace = new StackTraceElement[originalStackTrace.length + 1];
   System.arraycopy(originalStackTrace, 0, modifiedStackTrace, 1, originalStackTrace.length);
   modifiedStackTrace[0] = ste;
   langThrowable.setStackTrace(modifiedStackTrace);
   return langThrowable;
 }
 protected Throwable looseUnmarsalThrowable(OpenWireFormat wireFormat, DataInput dataIn)
     throws IOException {
   if (dataIn.readBoolean()) {
     String clazz = looseUnmarshalString(dataIn);
     String message = looseUnmarshalString(dataIn);
     Throwable o = createThrowable(clazz, message);
     if (wireFormat.isStackTraceEnabled()) {
       if (STACK_TRACE_ELEMENT_CONSTRUCTOR != null) {
         StackTraceElement ss[] = new StackTraceElement[dataIn.readShort()];
         for (int i = 0; i < ss.length; i++) {
           try {
             ss[i] =
                 (StackTraceElement)
                     STACK_TRACE_ELEMENT_CONSTRUCTOR.newInstance(
                         new Object[] {
                           looseUnmarshalString(dataIn),
                           looseUnmarshalString(dataIn),
                           looseUnmarshalString(dataIn),
                           Integer.valueOf(dataIn.readInt())
                         });
           } catch (IOException e) {
             throw e;
           } catch (Throwable e) {
           }
         }
         o.setStackTrace(ss);
       } else {
         short size = dataIn.readShort();
         for (int i = 0; i < size; i++) {
           looseUnmarshalString(dataIn);
           looseUnmarshalString(dataIn);
           looseUnmarshalString(dataIn);
           dataIn.readInt();
         }
       }
       o.initCause(looseUnmarsalThrowable(wireFormat, dataIn));
     }
     return o;
   } else {
     return null;
   }
 }
  private static Throwable toStackTrace(
      List<String> details, StackTraceElement[] parent, int index) {
    String detail = details.get(index++);
    if (!detail.startsWith("*")) {
      return null; // should not be happened. ignore remaining
    }
    int i1 = detail.indexOf(':');
    int i3 = detail.lastIndexOf(':');
    int i2 = detail.substring(0, i3).lastIndexOf(':');
    String exceptionClass = detail.substring(1, i1);
    String exceptionMessage = detail.substring(i1 + 1, i2);
    Throwable ex = newInstance(exceptionClass, exceptionMessage);

    int length = Integer.parseInt(detail.substring(i2 + 1, i3));
    int unique = Integer.parseInt(detail.substring(i3 + 1));

    int i = 0;
    StackTraceElement[] trace = new StackTraceElement[length];
    for (; i <= unique; i++) {
      detail = details.get(index++);
      int j1 = detail.indexOf(':');
      int j3 = detail.lastIndexOf(':');
      int j2 = detail.substring(0, j3).lastIndexOf(':');
      String className = detail.substring(0, j1);
      String methodName = detail.substring(j1 + 1, j2);
      String fileName = detail.substring(j2 + 1, j3);
      if (fileName.isEmpty()) {
        fileName = null;
      }
      int lineNumber = Integer.parseInt(detail.substring(j3 + 1));
      trace[i] = new StackTraceElement(className, methodName, fileName, lineNumber);
    }
    int common = trace.length - i;
    if (common > 0) {
      System.arraycopy(parent, parent.length - common, trace, trace.length - common, common);
    }
    if (details.size() > index) {
      ex.initCause(toStackTrace(details, trace, index));
    }
    ex.setStackTrace(trace);
    return ex;
  }
 @Override
 public void fail(final Throwable e) {
   if (failure != null) {
     throw new IllegalStateException(
         "Invalid ExternalTaskCompletionHandle as " + methodName + " failed with exception.",
         failure);
   }
   if (completed) {
     throw new IllegalStateException("Already completed");
   }
   if (stackTrace != null && !parent.isRethrown(e)) {
     AsyncStackTrace merged = new AsyncStackTrace(stackTrace, e.getStackTrace(), 0);
     merged.setStartFrom(getParentTaskMethodName());
     e.setStackTrace(merged.getStackTrace());
   }
   failure = e;
   if (!inCancellationHandler) {
     failToParent(e);
   }
 }
 @Override
 public void run() {
   if (canceled) {
     return;
   }
   setCurrent(parent);
   try {
     cancellationHandler = task.doExecute(completionHandle);
   } catch (Throwable e) {
     completionHandle.setDoExecuteFailed("ExternalTask.doExecute", e);
     if (stackTrace != null && !parent.isRethrown(e)) {
       AsyncStackTrace merged = new AsyncStackTrace(stackTrace, e.getStackTrace(), 0);
       merged.setStartFrom(getParentTaskMethodName());
       e.setStackTrace(merged.getStackTrace());
     }
     parent.fail(this, e);
   } finally {
     setCurrent(null);
   }
 }
Example #24
0
  public static void rewriteBlameStackTrace(final Throwable innerBlame) {
    final StackTraceElement[] stackTrace = innerBlame.getStackTrace();

    final List<StackTraceElement> innerStackTrace = new ArrayList<StackTraceElement>(10);
    final List<StackTraceElement> outerStackTrace = new ArrayList<StackTraceElement>(10);
    for (final StackTraceElement el : stackTrace) {
      if (el.getClassName().startsWith("org.jboss.errai.codegen.")) {
        innerStackTrace.add(el);
      } else {
        outerStackTrace.add(el);
      }
    }

    innerBlame.setStackTrace(
        innerStackTrace.toArray(new StackTraceElement[innerStackTrace.size()]));

    final RuntimeException outerBlame = new RuntimeException("External call to API");
    outerBlame.setStackTrace(
        outerStackTrace.toArray(new StackTraceElement[outerStackTrace.size()]));
    innerBlame.initCause(outerBlame);
  }
  private Throwable removeFrameworkFramesAndAppendStepLocation(
      Throwable error, StackTraceElement stepLocation) {
    StackTraceElement[] stackTraceElements = error.getStackTrace();
    if (stackTraceElements.length == 0 || stepLocation == null) {
      return error;
    }

    int newStackTraceLength;
    for (newStackTraceLength = 1;
        newStackTraceLength < stackTraceElements.length;
        ++newStackTraceLength) {
      if (stepDefinition.isDefinedAt(stackTraceElements[newStackTraceLength - 1])) {
        break;
      }
    }
    StackTraceElement[] newStackTrace = new StackTraceElement[newStackTraceLength + 1];
    System.arraycopy(stackTraceElements, 0, newStackTrace, 0, newStackTraceLength);
    newStackTrace[newStackTraceLength] = stepLocation;
    error.setStackTrace(newStackTrace);
    return error;
  }
Example #26
0
 @NotNull
 private static String renderStackTrace(@NotNull Throwable cause) {
   StackTraceElement[] oldTrace = cause.getStackTrace();
   List<StackTraceElement> newTrace = new ArrayList<StackTraceElement>();
   boolean skip = true;
   for (int i = oldTrace.length - 1; i >= 0; i--) {
     StackTraceElement element = oldTrace[i];
     // All our code happens in the script constructor, and no reflection/native code happens in
     // constructors.
     // So we ignore everything in the stack trace until the first constructor
     if (element.getMethodName().equals("<init>")) {
       skip = false;
     }
     if (!skip) {
       newTrace.add(element);
     }
   }
   Collections.reverse(newTrace);
   cause.setStackTrace(newTrace.toArray(new StackTraceElement[newTrace.size()]));
   return Throwables.getStackTraceAsString(cause);
 }
  /**
   * translate japid runtime exception to Play's TemplateExecutionException for formated error
   * reporting
   */
  static void handleException(Throwable e) throws RuntimeException {
    if (Play.mode == Mode.PROD) throw new RuntimeException(e);

    if (e instanceof TemplateExecutionException) throw (TemplateExecutionException) e;

    if (e instanceof RuntimeException && e.getCause() != null) e = e.getCause();
    // find the latest japidviews exception
    StackTraceElement[] stackTrace = e.getStackTrace();
    for (StackTraceElement ele : stackTrace) {
      String className = ele.getClassName();
      if (className.startsWith("japidviews")) {
        int lineNumber = ele.getLineNumber();
        RendererClass applicationClass = JapidPlayRenderer.japidClasses.get(className);
        //				ApplicationClass applicationClass = Play.classes.getApplicationClass(className);
        if (applicationClass != null) {
          // let's get the line of problem
          String jsrc = applicationClass.getSourceCode();
          String[] splitSrc = jsrc.split("\n");
          String line = splitSrc[lineNumber - 1];
          // can we have a line marker?
          int lineMarker = line.lastIndexOf("// line ");
          if (lineMarker > 0) {
            int oriLineNumber = Integer.parseInt(line.substring(lineMarker + 8).trim());
            StackTraceElement[] newStack = new StackTraceElement[stackTrace.length + 1];
            newStack[0] =
                new StackTraceElement(
                    className, "", applicationClass.getSrcFile().getPath(), oriLineNumber);
            System.arraycopy(stackTrace, 0, newStack, 1, stackTrace.length);
            e.setStackTrace(newStack);

            JapidPlayTemplate jpt = new JapidPlayTemplate();
            jpt.name = applicationClass.getSrcFile().getPath();
            jpt.source = applicationClass.getOriSourceCode();
            throw new TemplateExecutionException(jpt, oriLineNumber, e.getMessage(), e);
          }
        }
      }
    }
    throw new RuntimeException(e);
  }
 @Override
 public void run() {
   if (state == State.CLOSED) {
     return;
   }
   if (state == State.CREATED) {
     state = State.TRYING;
   }
   setCurrent(this);
   Throwable f = failure;
   try {
     switch (state) {
       case TRYING:
         if (canceled) {
           return;
         }
         tryCatchFinally.doTry();
         break;
       case CATCHING:
         failure = null;
         tryCatchFinally.doCatch(f);
         break;
       case FINALIZING:
         tryCatchFinally.doFinally();
     }
   } catch (Throwable e) {
     if (stackTrace != null && e != f) {
       AsyncStackTrace merged = new AsyncStackTrace(stackTrace, e.getStackTrace(), 0);
       merged.setStartFrom(getParentTaskMethodName());
       e.setStackTrace(merged.getStackTrace());
     }
     failure = e;
     cancelHeirs();
   } finally {
     setCurrent(null);
     executed = true;
     updateState();
   }
 }
  public Throwable filter(Throwable source) {
    if (shouldFilter) {
      StackTraceElement[] trace = source.getStackTrace();
      List<StackTraceElement> newTrace = filterTraceWithCutOff(trace, cutOffPackage);

      if (newTrace.isEmpty()) {
        // filter with no cut-off so at least there is some trace
        newTrace = filterTraceWithCutOff(trace, null);
      }

      // Only trim the trace if there was some application trace on the stack
      // if not we will just skip sanitizing and leave it as is
      if (!newTrace.isEmpty()) {
        // We don't want to lose anything, so log it
        STACK_LOG.error(FULL_STACK_TRACE_MESSAGE, source);
        StackTraceElement[] clean = new StackTraceElement[newTrace.size()];
        newTrace.toArray(clean);
        source.setStackTrace(clean);
      }
    }
    return source;
  }
Example #30
0
 private Throwable getCause(Method method, Throwable th) throws Throwable {
   Class<?> exTypes[] = method.getExceptionTypes();
   Throwable cause = th;
   Throwable lastThrowable = th;
   while (cause != null) {
     lastThrowable = cause;
     for (Class<?> exType : exTypes) {
       if (exType == cause.getClass()) {
         RuntimeException ex = new RuntimeException();
         StackTraceElement ste[] = ex.getStackTrace();
         StackTraceElement causeSte[] = lastThrowable.getStackTrace();
         StackTraceElement aggregateSte[] = new StackTraceElement[ste.length + causeSte.length];
         System.arraycopy(causeSte, 0, aggregateSte, 0, causeSte.length);
         System.arraycopy(ste, 0, aggregateSte, causeSte.length, ste.length);
         lastThrowable.setStackTrace(aggregateSte);
         throw lastThrowable;
       }
     }
     cause = cause.getCause();
   }
   throw lastThrowable;
 }