Example usage for javax.script ScriptException getLineNumber

List of usage examples for javax.script ScriptException getLineNumber

Introduction

In this page you can find the example usage for javax.script ScriptException getLineNumber.

Prototype

public int getLineNumber() 

Source Link

Document

Get the line number on which an error occurred.

Usage

From source file:com.espertech.esper.epl.script.jsr223.JSR223Helper.java

public static String getScriptCompileMsg(ScriptException ex) {
    if (ex.getLineNumber() != 1 && ex.getColumnNumber() != -1) {
        return "At line " + ex.getLineNumber() + " column " + ex.getColumnNumber() + ": " + ex.getMessage();
    } else {//  ww  w .ja  va2  s .  c om
        return ex.getMessage();
    }
}

From source file:com.intuit.tank.tools.script.ScriptRunner.java

/**
 * // www  . j  a  v  a 2s.c o m
 * @param scriptName
 * @param script
 * @param engine
 * @param inputs
 * @param output
 * @return
 * @throws ScriptException
 */
public ScriptIOBean runScript(@Nullable String scriptName, @Nonnull String script, @Nonnull ScriptEngine engine,
        @Nonnull Map<String, Object> inputs, OutputLogger output) throws ScriptException {
    Reader reader = null;
    ScriptIOBean ioBean = null;
    try {
        reader = new StringReader(script);
        ioBean = new ScriptIOBean(inputs, output);
        engine.put("ioBean", ioBean);
        ioBean.println("Starting test...");
        engine.eval(reader, engine.getContext());
        ioBean.println("Finished test...");
    } catch (ScriptException e) {
        throw new ScriptException(e.getMessage(), scriptName, e.getLineNumber(), e.getColumnNumber());
    } finally {
        IOUtils.closeQuietly(reader);
    }
    return ioBean;
}

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java

public void reportScriptFileError(File script, ScriptException e) {
    log.warn("Failed executing script: " + script.getPath() + ".");

    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    pw.println("Error on: " + script.getAbsolutePath());
    pw.println("Line: " + e.getLineNumber() + " - Column: " + e.getColumnNumber());
    pw.println();//w  w w . ja  va 2 s .c o m
    e.printStackTrace(pw);
    pw.close();

    final String report = sw.toString();

    FileOutputStream fos = null;
    try {
        String fileName = script.getName() + ".error.log";

        fos = new FileOutputStream(new File(script.getParent(), fileName));
        fos.write(report.getBytes());

        log.warn("See " + fileName + " for details.");
    } catch (IOException ioe) {
        log.warn("Additionally failed when trying to write an error report on script directory.", ioe);
        log.info(report);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java

public void reportScriptFileError(File script, ScriptException e) {
    _log.warn("Failed executing script: " + script.getPath() + ".");

    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    pw.println("Error on: " + script.getAbsolutePath());
    pw.println("Line: " + e.getLineNumber() + " - Column: " + e.getColumnNumber());
    pw.println();/* w w w  . jav  a2 s . com*/
    e.printStackTrace(pw);
    pw.close();

    final String report = sw.toString();

    FileOutputStream fos = null;
    try {
        String fileName = script.getName() + ".error.log";

        fos = new FileOutputStream(new File(script.getParent(), fileName));
        fos.write(report.getBytes());

        _log.warn("See " + fileName + " for details.");
    } catch (IOException ioe) {
        _log.warn("Additionally failed when trying to write an error report on script directory.", ioe);
        _log.info(report);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

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;
                }/*from   ww w. j a v  a 2s  . c  om*/
            }
        }
    }

    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());
    }
}

From source file:org.fit.cssbox.scriptbox.dom.Html5DocumentImpl.java

/**
 * Reports document's script error.//from w  w  w  .jav a  2 s.  co m
 * 
 * @see <a href=http://www.w3.org/html/wg/drafts/html/CR/webappapis.html#runtime-script-errors-in-documents">Runtime script errors in documents</a>
 */
public void reportScriptError(Script<?, ?, ?> script) {
    if (errorReportingMode) {
        return;
    }
    ScriptException scriptException = script.getException();
    Throwable rootException = ExceptionUtils.getRootCause(scriptException);

    if (scriptException == null) {
        return;
    }

    errorReportingMode = true;

    int lineno = scriptException.getLineNumber();
    int colno = scriptException.getColumnNumber();
    ;
    String message = rootException.getMessage();
    String location = _address.toExternalForm();
    Object errorObject = rootException; // TODO: Here should be an Error object

    if (script.hasMutedErros()) {
        message = "Script error.";
    }

    ErrorEvent errorEvent = new ErrorEvent();

    errorEvent.initEvent("error", false, true, message, location, lineno, colno, errorObject);

    errorReportingMode = false;

    _window.dispatchEvent(errorEvent);
}

From source file:org.freeplane.plugin.script.GenericScript.java

private void handleScriptRuntimeException(final ScriptException e) {
    outStream.print("message: " + e.getMessage());
    int lineNumber = e.getLineNumber();
    outStream.print("Line number: " + lineNumber);
    errorHandler.gotoLine(lineNumber);/* ww  w  . j  a  v  a  2  s  .c o  m*/
    throw new ExecuteScriptException(e.getMessage() + " at line " + lineNumber,
            // The ScriptException should have a cause. Use
            // that, it is what we want to know.
            (e.getCause() == null) ? e : e.getCause());
}

From source file:org.openadaptor.auxil.processor.script.ScriptProcessor.java

/**
 * Process a data item./* w  ww .  j  a  v a 2  s  .  c  o m*/
 * It will bind the data using the configured databinding, to
 * make it available to the script.
 * 
 * The bound object will be returned in a single Element Object[]
 * <br>
 * Note: If compilation is not possible, and the script is contained in a 
 * file, then the file will be read each time a datum is being processed. This
 * should be avoided for obvious reasons :-)
 */
protected Object[] doProcess(Object data) {
    if (data == null) { //conform to IDataProcessor contract.
        throw new NullRecordException("Null record not permitted");
    }
    //Clone it if possible.
    //data=ReflectionUtils.clone(data);
    data = cloner.clone(data);
    try {
        scriptEngine.put(metadataBinding, metadata);
        scriptEngine.put(dataBinding, data);
        if (compiledScript != null) {
            lastResult = compiledScript.eval();
        } else {
            if (script != null) {
                lastResult = scriptEngine.eval(script);
            } else {
                lastResult = scriptEngine.eval(new FileReader(scriptFilename));
            }
        }
        data = scriptEngine.get(dataBinding);
        if (data == null) {
            data = new Object[] {};
        } else {
            if (boxReturnedArrays || (!(data instanceof Object[]))) {
                data = new Object[] { data }; //Wrap it in an Object array.
            }
        }
        return (Object[]) data;
    } catch (ScriptException e) {
        log.debug("Script cause: " + e.getCause());

        throw new ProcessingException("failed to execute script, " + e.getMessage() + " line "
                + e.getLineNumber() + " col " + e.getColumnNumber(), e, this);
    } catch (FileNotFoundException e) {
        throw new ConnectionException("failed to load script file, " + e.getMessage() + scriptFilename, e,
                this);
    }
}

From source file:org.openadaptor.auxil.processor.script.ScriptProcessor.java

/**
 * Initialise the script engine.//from   w  w w .j a  v  a 2s .c  o m
 * <br>
 * This will create a script engine, and compile the supplied
 * script is compilation is possible, and enabled.
 * @throws ValidationException
 */
private void initialise() throws ValidationException {
    log.info("Initialising script engine for language: " + language);
    log.debug("Compile flag: " + compile);
    scriptEngine = createScriptEngine();
    if (compile && scriptEngine instanceof Compilable) {
        Compilable compilableScriptEngine = (Compilable) scriptEngine;
        try {
            if (script != null) {
                log.debug("Compiling script: " + script);
                compiledScript = compilableScriptEngine.compile(script);
            } else {
                log.debug("Compiling script from file: " + scriptFilename);
                compiledScript = compilableScriptEngine.compile(new FileReader(scriptFilename));
            }
            log.info("Script compiled successfully");
        } catch (ScriptException e) {
            String failMsg = "Failed to compile script, " + e.getMessage() + " line " + e.getLineNumber()
                    + " col " + e.getColumnNumber();
            log.warn(failMsg);
            throw new ValidationException(failMsg, e, this);
        } catch (FileNotFoundException e) {
            String failMsg = "Failed to compile script, " + e.getMessage();
            log.warn(failMsg);
            throw new ValidationException(failMsg, e, this);
        }
    }
    //Apply binding to allow scripts to access logging
    scriptEngine.put(logBinding, log);
    //Apply extra bindings, if any.
    applyBindings(scriptEngine, additionalBindings);
}

From source file:org.quackbot.hooks.loaders.JSHookLoader.java

protected Object invokeFunction(ScriptEngine jsEngine, Map<String, String> sourceMap, String functionName,
        Object... args) throws JSHookException {
    try {//from w w w.java  2 s  .  c om
        return ((Invocable) jsEngine).invokeFunction(functionName, args);
    } catch (ScriptException ex) {
        //Calculate where the exception occured at
        int lastLine = 0;
        for (Map.Entry<String, String> curEntry : sourceMap.entrySet()) {
            int fileLen = curEntry.getValue().split(System.getProperty("line.separator")).length;
            if (lastLine <= ex.getLineNumber() && ex.getLineNumber() >= fileLen)
                throw new JSHookException("Exception encountered when invoking function " + functionName,
                        curEntry.getKey(), ex.getLineNumber() - lastLine, ex.getColumnNumber(), ex);
            else
                lastLine += fileLen;
        }
        throw new JSHookException("Exception encountered when invoking function " + functionName, "unknown",
                ex.getLineNumber(), ex.getColumnNumber(), ex);
    } catch (NoSuchMethodException ex) {
        throw new JSHookException("Can't find function " + functionName + " in file(s) "
                + StringUtils.join(sourceMap.keySet().toArray()), ex);
    }
}