org.codehaus.groovy.runtime.StackTraceUtils Java Examples

The following examples show how to use org.codehaus.groovy.runtime.StackTraceUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RunScriptTool.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void run(CommandLine line, ToolRunningContext context) {
    Path file = context.getFileSystem().getPath(line.getOptionValue(FILE));
    if (file.getFileName().toString().endsWith(".groovy")) {
        try {
            Binding binding = new Binding();
            binding.setProperty("args", line.getArgs());
            GroovyScripts.run(file, binding, context.getOutputStream());
        } catch (Exception e) {
            Throwable rootCause = StackTraceUtils.sanitizeRootCause(e);
            rootCause.printStackTrace(context.getErrorStream());
        }
    } else {
        throw new IllegalArgumentException("Script type not supported");
    }
}
 
Example #2
Source File: StreamingTemplateEngine.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void error(int index, List<StringSection> sections, Throwable e) throws Throwable {
    int i = Math.max(0, index);
    StringSection precedingSection = sections.get(i);
    int traceLine = -1;
    for (StackTraceElement element : e.getStackTrace()) {
        if (element.getClassName().contains(TEMPLATE_SCRIPT_PREFIX)) {
            traceLine = element.getLineNumber();
            break;
        }
    }

    if (traceLine != -1) {
        int actualLine = precedingSection.lastSourcePosition.row + traceLine - 1;
        String message = "Template execution error at line " + actualLine + ":\n" + getErrorContext(actualLine);
        TemplateExecutionException unsanitized = new TemplateExecutionException(actualLine, message, StackTraceUtils.sanitize(e));
        throw StackTraceUtils.sanitize(unsanitized);
    } else {
        throw e;
    }
}
 
Example #3
Source File: GroovyCodeRunner.java    From beakerx with Apache License 2.0 6 votes vote down vote up
private TryResult handleError(String scriptName, Throwable e) {
  TryResult either;
  if (e instanceof InvocationTargetException) {
    e = ((InvocationTargetException) e).getTargetException();
  }

  if (e instanceof InterruptedException || e instanceof InvocationTargetException || e instanceof ThreadDeath) {
    either = TryResult.createError(INTERUPTED_MSG);
  } else {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    StackTraceUtils.sanitize(e).printStackTrace(pw);
    String value = sw.toString();
    value = printStacktrace(scriptName, value);
    either = TryResult.createError(value);
  }
  return either;
}
 
Example #4
Source File: GroovyInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public InterpreterResult interpret(String cmd, InterpreterContext contextInterpreter) {
  try {
    Script script = getGroovyScript(contextInterpreter.getParagraphId(), cmd);
    Job runningJob = getRunningJob(contextInterpreter.getParagraphId());
    runningJob.info()
        .put("CURRENT_THREAD", Thread.currentThread()); //to be able to terminate thread
    Map<String, Object> bindings = script.getBinding().getVariables();
    bindings.clear();
    StringWriter out = new StringWriter((int) (cmd.length() * 1.75));
    //put shared bindings evaluated in this interpreter
    bindings.putAll(sharedBindings);
    //put predefined bindings
    bindings.put("g", new GObject(log, out, this.getProperties(), contextInterpreter, bindings));
    bindings.put("out", new PrintWriter(out, true));

    script.run();
    //let's get shared variables defined in current script and store them in shared map
    for (Map.Entry<String, Object> e : bindings.entrySet()) {
      if (!predefinedBindings.contains(e.getKey())) {
        if (log.isTraceEnabled()) {
          log.trace("groovy script variable " + e);  //let's see what we have...
        }
        sharedBindings.put(e.getKey(), e.getValue());
      }
    }

    bindings.clear();
    InterpreterResult result = new InterpreterResult(Code.SUCCESS, out.toString());
    return result;
  } catch (Throwable t) {
    t = StackTraceUtils.deepSanitize(t);
    String msg = t.toString() + "\n at " + t.getStackTrace()[0];
    log.error("Failed to run script: " + t + "\n" + cmd + "\n", t);
    return new InterpreterResult(Code.ERROR, msg);
  }
}
 
Example #5
Source File: GradlePluginLord.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * This code was copied from BuildExceptionReporter.reportBuildFailure in gradle's source, then modified slightly to compensate for the fact that we're not driven by options or logging things to a
 * logger object.
 */
public static String getGradleExceptionMessage(Throwable failure, ShowStacktrace stackTraceLevel) {
    if (failure == null) {
        return "";
    }

    Formatter formatter = new Formatter();

    formatter.format("%nBuild failed.%n");

    if (stackTraceLevel == ShowStacktrace.INTERNAL_EXCEPTIONS) {
        formatter.format("Use the stack trace options to get more details.");
    }

    if (failure != null) {
        formatter.format("%n");

        if (failure instanceof LocationAwareException) {
            LocationAwareException scriptException = (LocationAwareException) failure;
            formatter.format("%s%n%n", scriptException.getLocation());
            formatter.format("%s", scriptException.getCause().getMessage());

            for (Throwable cause : scriptException.getReportableCauses()) {
                formatter.format("%nCause: %s", getMessage(cause));
            }
        } else {
            formatter.format("%s", getMessage(failure));
        }

        if (stackTraceLevel != ShowStacktrace.INTERNAL_EXCEPTIONS) {
            formatter.format("%n%nException is:\n");
            if (stackTraceLevel == ShowStacktrace.ALWAYS_FULL) {
                return formatter.toString() + getStackTraceAsText(failure);
            }

            return formatter.toString() + getStackTraceAsText(StackTraceUtils.deepSanitize(failure));
        }
    }

    return formatter.toString();
}
 
Example #6
Source File: StackTraceSanitizingExceptionAnalyser.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Throwable transform(Throwable exception) {
    return StackTraceUtils.deepSanitize(analyser.transform(exception));
}
 
Example #7
Source File: GradlePluginLord.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * This code was copied from BuildExceptionReporter.reportBuildFailure in gradle's source, then modified slightly to compensate for the fact that we're not driven by options or logging things to a
 * logger object.
 */
public static String getGradleExceptionMessage(Throwable failure, ShowStacktrace stackTraceLevel) {
    if (failure == null) {
        return "";
    }

    Formatter formatter = new Formatter();

    formatter.format("%nBuild failed.%n");

    if (stackTraceLevel == ShowStacktrace.INTERNAL_EXCEPTIONS) {
        formatter.format("Use the stack trace options to get more details.");
    }

    if (failure != null) {
        formatter.format("%n");

        if (failure instanceof LocationAwareException) {
            LocationAwareException scriptException = (LocationAwareException) failure;
            formatter.format("%s%n%n", scriptException.getLocation());
            formatter.format("%s", scriptException.getCause().getMessage());

            for (Throwable cause : scriptException.getReportableCauses()) {
                formatter.format("%nCause: %s", getMessage(cause));
            }
        } else {
            formatter.format("%s", getMessage(failure));
        }

        if (stackTraceLevel != ShowStacktrace.INTERNAL_EXCEPTIONS) {
            formatter.format("%n%nException is:\n");
            if (stackTraceLevel == ShowStacktrace.ALWAYS_FULL) {
                return formatter.toString() + getStackTraceAsText(failure);
            }

            return formatter.toString() + getStackTraceAsText(StackTraceUtils.deepSanitize(failure));
        }
    }

    return formatter.toString();
}
 
Example #8
Source File: BuildExceptionReporter.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void writeFailureDetails(StyledTextOutput output, FailureDetails details) {
    if (details.location.getHasContent()) {
        output.println();
        output.println("* Where:");
        details.location.writeTo(output);
        output.println();
    }

    if (details.details.getHasContent()) {
        output.println();
        output.println("* What went wrong:");
        details.details.writeTo(output);
        output.println();
    }

    if (details.resolution.getHasContent()) {
        output.println();
        output.println("* Try:");
        details.resolution.writeTo(output);
        output.println();
    }

    Throwable exception = null;
    switch (details.exceptionStyle) {
        case NONE:
            break;
        case SANITIZED:
            exception = StackTraceUtils.deepSanitize(details.failure);
            break;
        case FULL:
            exception = details.failure;
            break;
    }

    if (exception != null) {
        output.println();
        output.println("* Exception is:");
        output.exception(exception);
        output.println();
    }
}
 
Example #9
Source File: Exceptions.java    From ccu-historian with GNU General Public License v3.0 4 votes vote down vote up
public static void sanitize(Throwable t) {
	StackTraceUtils.sanitize(t);
	StackTraceUtils.sanitizeRootCause(t);
}
 
Example #10
Source File: GradlePluginLord.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * This code was copied from BuildExceptionReporter.reportBuildFailure in gradle's source, then modified slightly to compensate for the fact that we're not driven by options or logging things to a
 * logger object.
 */
public static String getGradleExceptionMessage(Throwable failure, ShowStacktrace stackTraceLevel) {
    if (failure == null) {
        return "";
    }

    Formatter formatter = new Formatter();

    formatter.format("%nBuild failed.%n");

    if (stackTraceLevel == ShowStacktrace.INTERNAL_EXCEPTIONS) {
        formatter.format("Use the stack trace options to get more details.");
    }

    if (failure != null) {
        formatter.format("%n");

        if (failure instanceof LocationAwareException) {
            LocationAwareException scriptException = (LocationAwareException) failure;
            formatter.format("%s%n%n", scriptException.getLocation());
            formatter.format("%s", scriptException.getCause().getMessage());

            for (Throwable cause : scriptException.getReportableCauses()) {
                formatter.format("%nCause: %s", getMessage(cause));
            }
        } else {
            formatter.format("%s", getMessage(failure));
        }

        if (stackTraceLevel != ShowStacktrace.INTERNAL_EXCEPTIONS) {
            formatter.format("%n%nException is:\n");
            if (stackTraceLevel == ShowStacktrace.ALWAYS_FULL) {
                return formatter.toString() + getStackTraceAsText(failure);
            }

            return formatter.toString() + getStackTraceAsText(StackTraceUtils.deepSanitize(failure));
        }
    }

    return formatter.toString();
}
 
Example #11
Source File: StackTraceSanitizingExceptionAnalyser.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public Throwable transform(Throwable exception) {
    return StackTraceUtils.deepSanitize(analyser.transform(exception));
}
 
Example #12
Source File: GradlePluginLord.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * This code was copied from BuildExceptionReporter.reportBuildFailure in gradle's source, then modified slightly to compensate for the fact that we're not driven by options or logging things to a
 * logger object.
 */
public static String getGradleExceptionMessage(Throwable failure, ShowStacktrace stackTraceLevel) {
    if (failure == null) {
        return "";
    }

    Formatter formatter = new Formatter();

    formatter.format("%nBuild failed.%n");

    if (stackTraceLevel == ShowStacktrace.INTERNAL_EXCEPTIONS) {
        formatter.format("Use the stack trace options to get more details.");
    }

    if (failure != null) {
        formatter.format("%n");

        if (failure instanceof LocationAwareException) {
            LocationAwareException scriptException = (LocationAwareException) failure;
            formatter.format("%s%n%n", scriptException.getLocation());
            formatter.format("%s", scriptException.getCause().getMessage());

            for (Throwable cause : scriptException.getReportableCauses()) {
                formatter.format("%nCause: %s", getMessage(cause));
            }
        } else {
            formatter.format("%s", getMessage(failure));
        }

        if (stackTraceLevel != ShowStacktrace.INTERNAL_EXCEPTIONS) {
            formatter.format("%n%nException is:\n");
            if (stackTraceLevel == ShowStacktrace.ALWAYS_FULL) {
                return formatter.toString() + getStackTraceAsText(failure);
            }

            return formatter.toString() + getStackTraceAsText(StackTraceUtils.deepSanitize(failure));
        }
    }

    return formatter.toString();
}
 
Example #13
Source File: BuildExceptionReporter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void writeFailureDetails(StyledTextOutput output, FailureDetails details) {
    if (details.location.getHasContent()) {
        output.println();
        output.println("* Where:");
        details.location.writeTo(output);
        output.println();
    }

    if (details.details.getHasContent()) {
        output.println();
        output.println("* What went wrong:");
        details.details.writeTo(output);
        output.println();
    }

    if (details.resolution.getHasContent()) {
        output.println();
        output.println("* Try:");
        details.resolution.writeTo(output);
        output.println();
    }

    Throwable exception = null;
    switch (details.exceptionStyle) {
        case NONE:
            break;
        case SANITIZED:
            exception = StackTraceUtils.deepSanitize(details.failure);
            break;
        case FULL:
            exception = details.failure;
            break;
    }

    if (exception != null) {
        output.println();
        output.println("* Exception is:");
        output.exception(exception);
        output.println();
    }
}
 
Example #14
Source File: ExecuteGroovyScript.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession _session) throws ProcessException {
    boolean toFailureOnError = VALID_FAIL_STRATEGY[1].equals(context.getProperty(FAIL_STRATEGY).getValue());
    //create wrapped session to control list of newly created and files got from this session.
    //so transfer original input to failure will be possible
    GroovyProcessSessionWrap session = new GroovyProcessSessionWrap(_session, toFailureOnError);

    Map<String, Object> CTL = new AccessMap("CTL");
    Map<String, Object> SQL = new AccessMap("SQL");
    Map<String, Object> RECORD_READER = new AccessMap("RecordReader");
    Map<String, Object> RECORD_SET_WRITER = new AccessMap("RecordSetWriter");

    try {
        Script script = getGroovyScript(); //compilation must be moved to validation
        Map bindings = script.getBinding().getVariables();

        bindings.clear();

        // Find the user-added properties and bind them for the script
        for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
            if (property.getKey().isDynamic()) {
                if (property.getKey().getName().startsWith("CTL.")) {
                    //get controller service
                    ControllerService ctl = context.getProperty(property.getKey()).asControllerService(ControllerService.class);
                    CTL.put(property.getKey().getName().substring(4), ctl);
                } else if (property.getKey().getName().startsWith("SQL.")) {
                    DBCPService dbcp = context.getProperty(property.getKey()).asControllerService(DBCPService.class);
                    SQL.put(property.getKey().getName().substring(4), dbcp);
                } else if (property.getKey().getName().startsWith("RecordReader.")) {
                    // Get RecordReaderFactory controller service
                    RecordReaderFactory recordReader = context.getProperty(property.getKey()).asControllerService(RecordReaderFactory.class);
                    RECORD_READER.put(property.getKey().getName().substring(13), recordReader);
                } else if (property.getKey().getName().startsWith("RecordWriter.")) {
                    // Get RecordWriterFactory controller service
                    RecordSetWriterFactory recordWriter = context.getProperty(property.getKey()).asControllerService(RecordSetWriterFactory.class);
                    RECORD_SET_WRITER.put(property.getKey().getName().substring(13), recordWriter);
                } else {
                    // Add the dynamic property bound to its full PropertyValue to the script engine
                    if (property.getValue() != null) {
                        bindings.put(property.getKey().getName(), context.getProperty(property.getKey()));
                    }
                }
            }
        }
        onInitSQL(SQL);

        bindings.put("session", session);
        bindings.put("context", context);
        bindings.put("log", getLogger());
        bindings.put("REL_SUCCESS", REL_SUCCESS);
        bindings.put("REL_FAILURE", REL_FAILURE);
        bindings.put("CTL", CTL);
        bindings.put("SQL", SQL);
        bindings.put("RecordReader", RECORD_READER);
        bindings.put("RecordWriter", RECORD_SET_WRITER);

        script.run();
        bindings.clear();

        onCommitSQL(SQL);
        session.commit();
    } catch (Throwable t) {
        getLogger().error(t.toString(), t);
        onFailSQL(SQL);
        if (toFailureOnError) {
            //transfer all received to failure with two new attributes: ERROR_MESSAGE and ERROR_STACKTRACE.
            session.revertReceivedTo(REL_FAILURE, StackTraceUtils.deepSanitize(t));
        } else {
            session.rollback(true);
        }
    } finally {
        onFinitSQL(SQL);
    }

}