Ejemplo n.º 1
0
 /**
  * Gets an approximate source code location for a node if possible.
  *
  * @return a file name and source line number in stack trace format (e.g. "String.java:32") if an
  *     approximate source location is found, null otherwise
  */
 public static String approxSourceLocation(Node node) {
   StackTraceElement[] stackTraceElements = approxSourceStackTraceElement(node);
   if (stackTraceElements != null && stackTraceElements.length > 0) {
     StackTraceElement top = stackTraceElements[0];
     if (top.getFileName() != null && top.getLineNumber() >= 0) {
       return top.getFileName() + ":" + top.getLineNumber();
     }
   }
   return null;
 }
  /** Checks all of the methods in gen for consistency */
  public static void checkMgens(final ClassGen gen) {

    if (skip_checks) return;

    Method[] methods = gen.getMethods();
    for (int i = 0; i < methods.length; i++) {
      Method method = methods[i];
      // System.out.println ("Checking method " + method + " in class "
      // + gen.getClassName());
      checkMgen(new MethodGen(method, gen.getClassName(), gen.getConstantPool()));
    }

    if (false) {
      Throwable t = new Throwable();
      t.fillInStackTrace();
      StackTraceElement[] ste = t.getStackTrace();
      StackTraceElement caller = ste[1];
      System.out.printf(
          "%s.%s (%s line %d)",
          caller.getClassName(),
          caller.getMethodName(),
          caller.getFileName(),
          caller.getLineNumber());
      for (int ii = 2; ii < ste.length; ii++)
        System.out.printf(" [%s line %d]", ste[ii].getFileName(), ste[ii].getLineNumber());
      System.out.printf("\n");
      dump_methods(gen);
    }
  }
Ejemplo n.º 3
0
  public void insertListOfCallPoints(@Nullable List<CallPoint> callPoints) {
    if (content.length() == 0) {
      content.append(EOL).append("      ");
    }

    content.append("  <ol style='display:none'>");

    if (callPoints == null) {
      content.append("</ol>").append(EOL).append("      ");
      return;
    }

    content.append(EOL);

    CallPoint currentCP = callPoints.get(0);
    appendTestMethod(currentCP.getStackTraceElement());
    appendRepetitionCountIfNeeded(currentCP);

    for (int i = 1, n = callPoints.size(); i < n; i++) {
      CallPoint nextCP = callPoints.get(i);
      StackTraceElement ste = nextCP.getStackTraceElement();

      if (nextCP.isSameTestMethod(currentCP)) {
        content.append(", ").append(ste.getLineNumber());
      } else {
        content.append("</li>").append(EOL);
        appendTestMethod(ste);
      }

      appendRepetitionCountIfNeeded(nextCP);
      currentCP = nextCP;
    }

    content.append("</li>").append(EOL).append("        </ol>").append(EOL).append("      ");
  }
Ejemplo n.º 4
0
  /**
   * This method duplicates the functionality of ExceptionUtils.describeStackLevels which is no
   * longer supported in Rice.
   *
   * @param fromLevel
   * @param toLevel
   * @return
   */
  public static String getMethodPath(int fromLevel, int toLevel) {
    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    // increase the levels to avoid including the method that called this.
    fromLevel = fromLevel + 1;
    toLevel = toLevel + 1;

    if (fromLevel <= 0) {
      throw new IllegalArgumentException("invalid fromLevel (" + fromLevel + " < 0)");
    }
    if (fromLevel > toLevel) {
      throw new IllegalArgumentException(
          "invalid levels (fromLevel " + fromLevel + " > toLevel " + toLevel + ")");
    }
    if (toLevel >= stackTraceElements.length) {
      throw new IllegalArgumentException(
          "invalid toLevel (" + toLevel + " >= " + stackTraceElements.length + ")");
    }

    StringBuffer result = new StringBuffer();
    int elementIndex = 0;
    for (StackTraceElement element : stackTraceElements) {
      if (elementIndex >= fromLevel && elementIndex >= toLevel) {
        if (result.length() > 0) {
          result.append(" from ");
        }
        result.append(element.getClassName()).append(".");
        result.append(element.getMethodName()).append("(");
        result.append(element.getFileName()).append(":");
        result.append(element.getLineNumber()).append(")");
      }
      elementIndex++;
    }
    return result.toString();
  }
Ejemplo n.º 5
0
    public static void printSite(Site s, StringBuilder out) {
      if (s == null) {
        out.append("(null)");
        return;
      }
      StackTraceElement[] st = s.site();

      int interestingSitesPrinted = 0;
      for (int i = s.offset; i < st.length; i++) {
        StackTraceElement e = st[i];
        String fileName = e.getFileName();
        if (THIS_FILE_NAME.equals(fileName)) {
          continue;
        }
        out.append(" " + e.getMethodName() + "(" + e.getFileName() + ":" + e.getLineNumber() + ")");
        interestingSitesPrinted++;
        if (interestingSitesPrinted <= SITES_TO_PRINT) {
          continue;
        }
        if (fileName == null || "View.java".equals(fileName)) {
          continue;
        }
        String methodName = e.getMethodName();
        if (skipMethods.contains(methodName)) {
          continue;
        }
        break;
      }
    }
Ejemplo n.º 6
0
  /**
   * Prints out the given debug message to System.out, prefixed by the calling class name, method
   * and line number, appending the stacktrace of the given exception.
   */
  public static void out(final String _debug_msg, final Throwable _exception) {
    String header = "DEBUG::";
    header = header + new Date(SystemTime.getCurrentTime()).toString() + "::";
    String className;
    String methodName;
    int lineNumber;
    String trace_trace_tail = null;

    try {
      throw new Exception();
    } catch (Exception e) {
      StackTraceElement[] st = e.getStackTrace();

      StackTraceElement first_line = st[2];
      className = first_line.getClassName() + "::";
      methodName = first_line.getMethodName() + "::";
      lineNumber = first_line.getLineNumber();

      trace_trace_tail = getCompressedStackTrace(e, 3, 200, false);
    }

    diagLoggerLogAndOut(header + className + (methodName) + lineNumber + ":", true);
    if (_debug_msg.length() > 0) {
      diagLoggerLogAndOut("  " + _debug_msg, true);
    }
    if (trace_trace_tail != null) {
      diagLoggerLogAndOut("    " + trace_trace_tail, true);
    }
    if (_exception != null) {
      diagLoggerLogAndOut(_exception);
    }
  }
Ejemplo n.º 7
0
 private void appendTestMethod(@Nonnull StackTraceElement current) {
   content.append("          <li>");
   content.append(current.getClassName()).append('#');
   content
       .append(LESS_THAN_CHAR.matcher(current.getMethodName()).replaceFirst("&lt;"))
       .append(": ");
   content.append(current.getLineNumber());
 }
Ejemplo n.º 8
0
 public static void printElement(Site s, int index) {
   if (s == null || index >= s.site().length) {
     ps.print("(null)");
   } else {
     StackTraceElement e = s.site()[index];
     ps.print(e.getMethodName() + " (" + e.getFileName() + ":" + e.getLineNumber() + ")");
   }
 }
Ejemplo n.º 9
0
  public static void printStackTrace(Throwable e, Object context) {
    String header = "DEBUG::";
    header = header + new Date(SystemTime.getCurrentTime()).toString() + "::";
    String className = "?::";
    String methodName = "?::";
    int lineNumber = -1;

    try {
      throw new Exception();
    } catch (Exception f) {
      StackTraceElement[] st = f.getStackTrace();

      for (int i = 1; i < st.length; i++) {
        StackTraceElement first_line = st[i];
        className = first_line.getClassName() + "::";
        methodName = first_line.getMethodName() + "::";
        lineNumber = first_line.getLineNumber();

        // skip stuff generated by the logger

        if (className.indexOf(".logging.") != -1 || className.endsWith(".Debug::")) {

          continue;
        }

        break;
      }
    }

    diagLoggerLogAndOut(header + className + (methodName) + lineNumber + ":", true);

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos));

      if (context != null) {
        pw.print("  ");
        pw.println(context);
      }
      pw.print("  ");
      e.printStackTrace(pw);

      pw.close();

      String stack = baos.toString();

      diagLoggerLogAndOut(stack, true);
    } catch (Throwable ignore) {

      e.printStackTrace();
    }
  }
Ejemplo n.º 10
0
 private static void printElementInfo(OutputStream stream, StackTraceElement element) {
   print(stream, element.getClassName());
   print(stream, ":");
   print(stream, element.getMethodName());
   print(stream, " ");
   print(stream, "(");
   print(stream, element.getFileName());
   print(stream, ":");
   print(stream, element.getLineNumber());
   print(stream, ")");
   printNewLine(stream);
 }
Ejemplo n.º 11
0
 protected String getTitle(Throwable t) {
   String message = t.getMessage();
   String tit = message;
   if (tit == null) {
     StackTraceElement el = t.getStackTrace()[0];
     tit =
         t.getClass().getName().substring(t.getClass().getPackage().getName().length() + 1)
             + " "
             + el.getFileName()
             + ":"
             + el.getLineNumber();
   }
   return tit;
 }
Ejemplo n.º 12
0
 @Override
 public int hashCode() {
   if (hashCode == 0) {
     int res = 1 + site.length * 17;
     int max = Math.max(site.length, 10);
     for (int i = offset; i < max; i++) {
       StackTraceElement e = site[i];
       int lineNumber = e.getLineNumber();
       res = res * 19 + 31 * lineNumber;
     }
     hashCode = res;
   }
   return hashCode;
 }
Ejemplo n.º 13
0
 private static void printThrowable(OutputStream stream, Throwable throwable) {
   printBytes(stream, ("Exception " + throwable.toString()).getBytes());
   printNewLine(stream);
   StackTraceElement[] stackTraceElements = throwable.getStackTrace();
   for (int i = stackTraceElements.length - 1; i >= 0; i--) {
     StackTraceElement element = stackTraceElements[i];
     printBytes(stream, element.getFileName().getBytes());
     printBytes(stream, ":".getBytes());
     printBytes(stream, String.valueOf(element.getLineNumber()).getBytes());
     printNewLine(stream);
   }
   if (throwable.getCause() != null) {
     printBytes(stream, "Caused by:\n".getBytes());
     printThrowable(stream, throwable.getCause());
   }
 }
Ejemplo n.º 14
0
 public static void printElements(Site s, int index, int nelems) {
   if (s == null || index >= s.site().length) {
     ps.print("(null)");
   } else {
     for (int i = 0; i < nelems; i++) {
       int j = index + i;
       if (j >= s.site().length) {
         break;
       }
       if (i > 0) {
         ps.print(", ");
       }
       StackTraceElement e = s.site()[j];
       ps.print(e.getMethodName() + " (" + e.getFileName() + ":" + e.getLineNumber() + ")");
     }
   }
 }
Ejemplo n.º 15
0
  public static void invoke(Http.Request request, Http.Response response) {
    Monitor monitor = null;

    try {

      resolve(request, response);
      Method actionMethod = request.invokedMethod;

      // 1. Prepare request params
      Scope.Params.current().__mergeWith(request.routeArgs);

      // add parameters from the URI query string
      String encoding = Http.Request.current().encoding;
      Scope.Params.current()
          ._mergeWith(
              UrlEncodedParser.parseQueryString(
                  new ByteArrayInputStream(request.querystring.getBytes(encoding))));

      // 2. Easy debugging ...
      if (Play.mode == Play.Mode.DEV) {
        Controller.class.getDeclaredField("params").set(null, Scope.Params.current());
        Controller.class.getDeclaredField("request").set(null, Http.Request.current());
        Controller.class.getDeclaredField("response").set(null, Http.Response.current());
        Controller.class.getDeclaredField("session").set(null, Scope.Session.current());
        Controller.class.getDeclaredField("flash").set(null, Scope.Flash.current());
        Controller.class.getDeclaredField("renderArgs").set(null, Scope.RenderArgs.current());
        Controller.class.getDeclaredField("routeArgs").set(null, Scope.RouteArgs.current());
        Controller.class.getDeclaredField("validation").set(null, Validation.current());
      }

      ControllerInstrumentation.stopActionCall();
      Play.pluginCollection.beforeActionInvocation(actionMethod);

      // Monitoring
      monitor = MonitorFactory.start(request.action + "()");

      // 3. Invoke the action
      try {
        // @Before
        handleBefores(request);

        // Action

        Result actionResult = null;
        String cacheKey = null;

        // Check the cache (only for GET or HEAD)
        if ((request.method.equals("GET") || request.method.equals("HEAD"))
            && actionMethod.isAnnotationPresent(CacheFor.class)) {
          cacheKey = actionMethod.getAnnotation(CacheFor.class).id();
          if ("".equals(cacheKey)) {
            cacheKey = "urlcache:" + request.url + request.querystring;
          }
          actionResult = (Result) play.cache.Cache.get(cacheKey);
        }

        if (actionResult == null) {
          ControllerInstrumentation.initActionCall();
          try {
            inferResult(invokeControllerMethod(actionMethod));
          } catch (InvocationTargetException ex) {
            // It's a Result ? (expected)
            if (ex.getTargetException() instanceof Result) {
              actionResult = (Result) ex.getTargetException();
              // Cache it if needed
              if (cacheKey != null) {
                play.cache.Cache.set(
                    cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
              }

            } else {
              // @Catch
              Object[] args = new Object[] {ex.getTargetException()};
              List<Method> catches =
                  Java.findAllAnnotatedMethods(Controller.getControllerClass(), Catch.class);
              Collections.sort(
                  catches,
                  new Comparator<Method>() {

                    public int compare(Method m1, Method m2) {
                      Catch catch1 = m1.getAnnotation(Catch.class);
                      Catch catch2 = m2.getAnnotation(Catch.class);
                      return catch1.priority() - catch2.priority();
                    }
                  });
              ControllerInstrumentation.stopActionCall();
              for (Method mCatch : catches) {
                Class[] exceptions = mCatch.getAnnotation(Catch.class).value();
                if (exceptions.length == 0) {
                  exceptions = new Class[] {Exception.class};
                }
                for (Class exception : exceptions) {
                  if (exception.isInstance(args[0])) {
                    mCatch.setAccessible(true);
                    inferResult(invokeControllerMethod(mCatch, args));
                    break;
                  }
                }
              }

              throw ex;
            }
          }
        }

        // @After
        handleAfters(request);

        monitor.stop();
        monitor = null;

        // OK, re-throw the original action result
        if (actionResult != null) {
          throw actionResult;
        }

        throw new NoResult();

      } catch (IllegalAccessException ex) {
        throw ex;
      } catch (IllegalArgumentException ex) {
        throw ex;
      } catch (InvocationTargetException ex) {
        // It's a Result ? (expected)
        if (ex.getTargetException() instanceof Result) {
          throw (Result) ex.getTargetException();
        }
        // Re-throw the enclosed exception
        if (ex.getTargetException() instanceof PlayException) {
          throw (PlayException) ex.getTargetException();
        }
        StackTraceElement element =
            PlayException.getInterestingStrackTraceElement(ex.getTargetException());
        if (element != null) {
          throw new JavaExecutionException(
              Play.classes.getApplicationClass(element.getClassName()),
              element.getLineNumber(),
              ex.getTargetException());
        }
        throw new JavaExecutionException(Http.Request.current().action, ex);
      }

    } catch (Result result) {

      Play.pluginCollection.onActionInvocationResult(result);

      // OK there is a result to apply
      // Save session & flash scope now

      Scope.Session.current().save();
      Scope.Flash.current().save();

      result.apply(request, response);

      Play.pluginCollection.afterActionInvocation();

      // @Finally
      handleFinallies(request, null);

    } catch (PlayException e) {
      handleFinallies(request, e);
      throw e;
    } catch (Throwable e) {
      handleFinallies(request, e);
      throw new UnexpectedException(e);
    } finally {
      if (monitor != null) {
        monitor.stop();
      }
    }
  }
Ejemplo n.º 16
0
  /**
   * Format the given message to XML.
   *
   * @param record the log record to be formatted.
   * @return a formatted log record
   */
  public String format(LogRecord record0) {
    if (!(record0 instanceof TopLinkLogRecord)) {
      return super.format(record0);
    } else {
      TopLinkLogRecord record = (TopLinkLogRecord) record0;

      StringBuffer sb = new StringBuffer(500);
      sb.append("<record>\n");

      if (record.shouldPrintDate()) {
        sb.append("  <date>");
        appendISO8601(sb, record.getMillis());
        sb.append("</date>\n");

        sb.append("  <millis>");
        sb.append(record.getMillis());
        sb.append("</millis>\n");
      }

      sb.append("  <sequence>");
      sb.append(record.getSequenceNumber());
      sb.append("</sequence>\n");

      String name = record.getLoggerName();
      if (name != null) {
        sb.append("  <logger>");
        escape(sb, name);
        sb.append("</logger>\n");
      }

      sb.append("  <level>");
      escape(sb, record.getLevel().toString());
      sb.append("</level>\n");

      if (record.getSourceClassName() != null) {
        sb.append("  <class>");
        escape(sb, record.getSourceClassName());
        sb.append("</class>\n");
      }

      if (record.getSourceMethodName() != null) {
        sb.append("  <method>");
        escape(sb, record.getSourceMethodName());
        sb.append("</method>\n");
      }

      if (record.getSessionString() != null) {
        sb.append("  <session>");
        sb.append(record.getSessionString());
        sb.append("</session>\n");
      }

      if (record.getConnection() != null) {
        sb.append("  <connection>");
        sb.append(String.valueOf(System.identityHashCode(record.getConnection())));
        sb.append("</connection>\n");
      }

      if (record.shouldPrintThread()) {
        sb.append("  <thread>");
        sb.append(record.getThreadID());
        sb.append("</thread>\n");
      }

      if (record.getMessage() != null) {
        // Format the message string and its accompanying parameters.
        String message = formatMessage(record);
        sb.append("  <message>");
        escape(sb, message);
        sb.append("</message>");
        sb.append("\n");
      }

      // If the message is being localized, output the key, resource
      // bundle name, and params.
      ResourceBundle bundle = record.getResourceBundle();
      try {
        if ((bundle != null) && (bundle.getString(record.getMessage()) != null)) {
          sb.append("  <key>");
          escape(sb, record.getMessage());
          sb.append("</key>\n");
          sb.append("  <catalog>");
          escape(sb, record.getResourceBundleName());
          sb.append("</catalog>\n");
          Object[] parameters = record.getParameters();
          for (int i = 0; i < parameters.length; i++) {
            sb.append("  <param>");
            try {
              escape(sb, parameters[i].toString());
            } catch (Exception ex) {
              sb.append("???");
            }
            sb.append("</param>\n");
          }
        }
      } catch (Exception ex) {
        // The message is not in the catalog.  Drop through.
      }

      if (record.getThrown() != null) {
        // Report on the state of the throwable.
        Throwable th = record.getThrown();
        sb.append("  <exception>\n");
        sb.append("    <message>");
        escape(sb, th.toString());
        sb.append("</message>\n");

        if ((record.getLevel().intValue() == Level.SEVERE.intValue())
            || ((record.getLevel().intValue() <= Level.WARNING.intValue())
                && record.shouldLogExceptionStackTrace())) {
          StackTraceElement[] trace = th.getStackTrace();
          for (int i = 0; i < trace.length; i++) {
            StackTraceElement frame = trace[i];
            sb.append("    <frame>\n");
            sb.append("      <class>");
            escape(sb, frame.getClassName());
            sb.append("</class>\n");
            sb.append("      <method>");
            escape(sb, frame.getMethodName());
            sb.append("</method>\n");
            // Check for a line number.
            if (frame.getLineNumber() >= 0) {
              sb.append("      <line>");
              sb.append(frame.getLineNumber());
              sb.append("</line>\n");
            }
            sb.append("    </frame>\n");
          }
        }

        sb.append("  </exception>\n");
      }

      sb.append("</record>\n");
      return sb.toString();
    }
  }
Ejemplo n.º 17
0
  /**
   * Checks and calla all methods in controller annotated with @Finally. The caughtException-value
   * is sent as argument to @Finally-method if method has one argument which is Throwable
   *
   * @param request
   * @param caughtException If @Finally-methods are called after an error, this variable holds the
   *     caught error
   * @throws PlayException
   */
  static void handleFinallies(Http.Request request, Throwable caughtException)
      throws PlayException {

    if (Controller.getControllerClass() == null) {
      // skip it
      return;
    }

    try {
      List<Method> allFinally =
          Java.findAllAnnotatedMethods(Controller.getControllerClass(), Finally.class);
      Collections.sort(
          allFinally,
          new Comparator<Method>() {

            public int compare(Method m1, Method m2) {
              Finally finally1 = m1.getAnnotation(Finally.class);
              Finally finally2 = m2.getAnnotation(Finally.class);
              return finally1.priority() - finally2.priority();
            }
          });
      ControllerInstrumentation.stopActionCall();
      for (Method aFinally : allFinally) {
        String[] unless = aFinally.getAnnotation(Finally.class).unless();
        String[] only = aFinally.getAnnotation(Finally.class).only();
        boolean skip = false;
        for (String un : only) {
          if (!un.contains(".")) {
            un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
          }
          if (un.equals(request.action)) {
            skip = false;
            break;
          } else {
            skip = true;
          }
        }
        for (String un : unless) {
          if (!un.contains(".")) {
            un = aFinally.getDeclaringClass().getName().substring(12) + "." + un;
          }
          if (un.equals(request.action)) {
            skip = true;
            break;
          }
        }
        if (!skip) {
          aFinally.setAccessible(true);

          // check if method accepts Throwable as only parameter
          Class[] parameterTypes = aFinally.getParameterTypes();
          if (parameterTypes.length == 1 && parameterTypes[0] == Throwable.class) {
            // invoking @Finally method with caughtException as parameter
            invokeControllerMethod(aFinally, new Object[] {caughtException});
          } else {
            // invoce @Finally-method the regular way without caughtException
            invokeControllerMethod(aFinally, null);
          }
        }
      }
    } catch (InvocationTargetException ex) {
      StackTraceElement element =
          PlayException.getInterestingStrackTraceElement(ex.getTargetException());
      if (element != null) {
        throw new JavaExecutionException(
            Play.classes.getApplicationClass(element.getClassName()),
            element.getLineNumber(),
            ex.getTargetException());
      }
      throw new JavaExecutionException(Http.Request.current().action, ex);
    } catch (Exception e) {
      throw new UnexpectedException("Exception while doing @Finally", e);
    }
  }