use of org.matheclipse.core.eval.exception.AbortException in project symja_android_library by axkr.
the class AJAXQueryServlet method evaluateString.
private String[] evaluateString(EvalEngine engine, final String inputString, final String numericMode, final String function, StringWriter outWriter, StringWriter errorWriter) {
String input = inputString.trim();
if (input.length() > 1 && input.charAt(0) == '?') {
IExpr doc = Documentation.findDocumentation(input);
return JSONBuilder.createJSONResult(engine, doc, outWriter, errorWriter);
}
try {
EvalEngine.setReset(engine);
ExprParser parser = new ExprParser(engine, isRelaxedSyntax());
// throws SyntaxError exception, if syntax isn't valid
IExpr inExpr = parser.parse(input);
if (inExpr != null) {
long numberOfLeaves = inExpr.leafCount();
if (numberOfLeaves > Config.MAX_INPUT_LEAVES) {
return JSONBuilder.createJSONError("Input expression too big!");
}
if (numericMode.equals("N")) {
inExpr = F.N(inExpr);
}
// inExpr contains the user input from the web interface in
// internal format now
StringWriter outBuffer = new StringWriter();
IExpr outExpr;
outExpr = evalTopLevel(engine, outBuffer, inExpr);
if (outExpr != null) {
if (outExpr.isAST(S.Graphics)) {
try {
String html = Config.SVG_PAGE;
StringBuilder stw = new StringBuilder();
GraphicsFunctions.graphicsToSVG((IAST) outExpr, stw);
html = StringUtils.replace(html, "`1`", stw.toString());
html = StringEscapeUtils.escapeHtml4(html);
return JSONBuilder.createJSONJavaScript("<iframe srcdoc=\"" + html + "\" style=\"display: block; width: 100%; height: 100%; border: none;\" ></iframe>");
} catch (Exception ex) {
LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
}
} else if (outExpr.isASTSizeGE(S.Graphics3D, 2)) {
StringBuilder buf = new StringBuilder();
if (GraphicsFunctions.renderGraphics3D(buf, (IAST) outExpr, engine)) {
try {
return JSONBuilder.createGraphics3DIFrame(JSBuilder.GRAPHICS3D_IFRAME_TEMPLATE, buf.toString());
} catch (Exception ex) {
LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
}
}
}
if (outExpr.isASTSizeGE(S.Show, 2)) {
IAST show = (IAST) outExpr;
return JSONBuilder.createJSONShow(engine, show);
} else if (outExpr instanceof GraphExpr) {
String javaScriptStr = GraphFunctions.graphToJSForm((GraphExpr) outExpr);
if (javaScriptStr != null) {
String html = VISJS_IFRAME;
html = StringUtils.replace(html, "`1`", javaScriptStr);
html = //
StringUtils.replace(//
html, //
"`2`", //
" var options = { };\n");
html = StringEscapeUtils.escapeHtml4(html);
return JSONBuilder.createJSONJavaScript("<iframe srcdoc=\"" + html + "\" style=\"display: block; width: 100%; height: 100%; border: none;\" ></iframe>");
}
} else if (outExpr instanceof ASTDataset) {
String javaScriptStr = ((ASTDataset) outExpr).datasetToJSForm();
if (javaScriptStr != null) {
String htmlSnippet = javaScriptStr.trim();
// html = StringEscapeUtils.escapeHtml4(html);
return JSONBuilder.createJSONHTML(engine, htmlSnippet, outWriter, errorWriter);
// return JSONBuilder.createJSONJavaScript(
// "<iframe srcdoc=\""
// + html
// + "\" style=\"display: block; width: 100%; height: 100%;
// border: none;\"></iframe>");
}
} else if (outExpr.isAST(S.JSFormData, 3)) {
IAST jsFormData = (IAST) outExpr;
String jsLibraryType = jsFormData.arg2().toString();
if (jsLibraryType.equals("mathcell")) {
try {
return JSONBuilder.createMathcellIFrame(JSBuilder.MATHCELL_IFRAME_TEMPLATE, jsFormData.arg1().toString());
} catch (Exception ex) {
LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
}
} else if (jsLibraryType.equals("jsxgraph")) {
try {
return JSONBuilder.createJSXGraphIFrame(JSBuilder.JSXGRAPH_IFRAME_TEMPLATE, jsFormData.arg1().toString());
} catch (Exception ex) {
LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
}
} else if (jsLibraryType.equals("plotly")) {
try {
return JSONBuilder.createPlotlyIFrame(JSBuilder.PLOTLY_IFRAME_TEMPLATE, jsFormData.arg1().toString());
} catch (Exception ex) {
LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
}
} else if (jsLibraryType.equals("treeform")) {
try {
String manipulateStr = jsFormData.arg1().toString();
String html = VISJS_IFRAME;
html = StringUtils.replace(html, "`1`", manipulateStr);
html = //
StringUtils.replace(//
html, //
"`2`", " var options = {\n" + " edges: {\n" + " smooth: {\n" + " type: 'cubicBezier',\n" + " forceDirection: 'vertical',\n" + " roundness: 0.4\n" + " }\n" + " },\n" + " layout: {\n" + " hierarchical: {\n" + " direction: \"UD\"\n" + " }\n" + " },\n" + " nodes: {\n" + " shape: 'box'\n" + " },\n" + " physics:false\n" + //
" }; ");
html = StringEscapeUtils.escapeHtml4(html);
return JSONBuilder.createJSONJavaScript("<iframe srcdoc=\"" + html + "\" style=\"display: block; width: 100%; height: 100%; border: none;\" ></iframe>");
} catch (Exception ex) {
LOGGER.debug("{}.evaluateString() failed", getClass().getSimpleName(), ex);
}
}
} else if (outExpr.isString()) {
IStringX str = (IStringX) outExpr;
if (str.getMimeType() == IStringX.TEXT_HTML) {
String htmlSnippet = str.toString();
String htmlPage = HTML_IFRAME;
htmlPage = StringUtils.replace(htmlPage, "`1`", htmlSnippet);
return JSONBuilder.createJSONJavaScript("<iframe srcdoc=\"" + htmlPage + "\" style=\"display: block; width: 100%; height: 100%; border: none;\" ></iframe>");
}
}
return JSONBuilder.createJSONResult(engine, outExpr, outWriter, errorWriter);
}
return createOutput(outBuffer, null, engine, function);
} else {
return JSONBuilder.createJSONError("Input string parsed to null");
}
} catch (AbortException se) {
return JSONBuilder.createJSONResult(engine, S.$Aborted, outWriter, errorWriter);
} catch (FailedException se) {
return JSONBuilder.createJSONResult(engine, S.$Failed, outWriter, errorWriter);
} catch (SyntaxError se) {
return JSONBuilder.createJSONSyntaxError(se.getMessage());
} catch (MathException se) {
return JSONBuilder.createJSONError(se.getMessage());
} catch (IOException e) {
String msg = e.getMessage();
if (msg != null) {
return JSONBuilder.createJSONError("IOException occured: " + msg);
}
return JSONBuilder.createJSONError("IOException occured");
} catch (Exception e) {
// error message
LOGGER.error("{}.evaluateString() failed", getClass().getSimpleName(), e);
String msg = e.getMessage();
if (msg != null) {
return JSONBuilder.createJSONError("Error in evaluateString: " + msg);
}
return JSONBuilder.createJSONError("Error in evaluateString: " + e.getClass().getSimpleName());
}
}
use of org.matheclipse.core.eval.exception.AbortException in project symja_android_library by axkr.
the class AbstractRubiTestCase method interpreter.
/**
* Evaluates the given string-expression and returns the result in <code>OutputForm</code>
*/
public String interpreter(final String inputExpression, final String expectedResult, String manuallyCheckedResult) {
IExpr result;
final StringWriter buf = new StringWriter();
IExpr integral = fEvaluator.parse(inputExpression).first();
try {
if (fSeconds <= 0) {
result = fEvaluator.eval(inputExpression);
} else {
EvalEngine engine = fEvaluator.getEvalEngine();
engine.setSeconds(fSeconds);
result = fEvaluator.evaluateWithTimeout(inputExpression, fSeconds, TimeUnit.SECONDS, true, new EvalControlledCallable(fEvaluator.getEvalEngine()));
}
if (result != null) {
return printResult(integral, result, expectedResult, manuallyCheckedResult);
}
} catch (final AbortException re) {
return printResult(integral, F.$Aborted, expectedResult, manuallyCheckedResult);
} catch (final FailedException re) {
return printResult(integral, F.$Failed, expectedResult, manuallyCheckedResult);
} catch (final SyntaxError se) {
String msg = se.getMessage();
System.err.println(msg);
System.err.println();
System.err.flush();
return "";
} catch (final RuntimeException re) {
Throwable me = re.getCause();
if (me instanceof MathException) {
Validate.printException(buf, me);
} else {
Validate.printException(buf, re);
}
System.err.println(buf.toString());
System.err.flush();
return "";
} catch (final Exception e) {
Validate.printException(buf, e);
System.err.println(buf.toString());
System.err.flush();
return "";
} catch (final OutOfMemoryError e) {
Validate.printException(buf, e);
System.err.println(buf.toString());
System.err.flush();
return "";
} catch (final StackOverflowError e) {
Validate.printException(buf, e);
System.err.println(buf.toString());
System.err.flush();
return "";
}
return buf.toString();
}
use of org.matheclipse.core.eval.exception.AbortException in project symja_android_library by axkr.
the class AbstractRubiTestCase method interpreter.
/**
* Evaluates the given string-expression and returns the result in <code>OutputForm</code>
*/
public String interpreter(final String inputExpression, final String expectedResult, String manuallyCheckedResult) {
IExpr result;
final StringWriter buf = new StringWriter();
try {
if (fSeconds <= 0) {
result = fEvaluator.eval(inputExpression);
} else {
EvalEngine engine = fEvaluator.getEvalEngine();
engine.setSeconds(fSeconds);
result = fEvaluator.evaluateWithTimeout(inputExpression, fSeconds, TimeUnit.SECONDS, true, new EvalControlledCallable(fEvaluator.getEvalEngine()));
}
if (result != null) {
return printResult(result, expectedResult, manuallyCheckedResult);
}
} catch (final AbortException re) {
return printResult(F.$Aborted, expectedResult, manuallyCheckedResult);
} catch (final FailedException re) {
return printResult(F.$Failed, expectedResult, manuallyCheckedResult);
} catch (final SyntaxError se) {
String msg = se.getMessage();
System.err.println(msg);
System.err.println();
System.err.flush();
return "";
} catch (final RuntimeException re) {
Throwable me = re.getCause();
if (me instanceof MathException) {
Validate.printException(buf, me);
} else {
Validate.printException(buf, re);
}
System.err.println(buf.toString());
System.err.flush();
return "";
} catch (final Exception e) {
Validate.printException(buf, e);
System.err.println(buf.toString());
System.err.flush();
return "";
} catch (final OutOfMemoryError e) {
Validate.printException(buf, e);
System.err.println(buf.toString());
System.err.flush();
return "";
} catch (final StackOverflowError e) {
Validate.printException(buf, e);
System.err.println(buf.toString());
System.err.flush();
return "";
}
return buf.toString();
}
use of org.matheclipse.core.eval.exception.AbortException in project symja_android_library by axkr.
the class SymjaBot method interpreter.
private static String interpreter(final String trimmedInput) {
ExprEvaluator evaluator = new ExprEvaluator(false, (short) 100);
IExpr result;
final StringWriter buf = new StringWriter();
try {
if (trimmedInput.length() > 1 && trimmedInput.charAt(0) == '?') {
StringBuilder docBuf = new StringBuilder();
Documentation.getMarkdown(docBuf, trimmedInput.substring(1));
String docString = docBuf.toString();
if (docString.length() > 0) {
int indx = docString.indexOf("### Github");
if (indx > 0) {
docString = docString.substring(0, indx);
}
return docString;
}
Documentation.usageDocumentation(docBuf, trimmedInput.substring(1));
docString = docBuf.toString();
if (docString.length() > 0) {
int indx = docString.indexOf("### Github");
if (indx > 0) {
docString = docString.substring(0, indx);
}
return docString;
}
return "No help page found";
}
System.out.println(trimmedInput);
result = evaluator.evaluateWithTimeout(trimmedInput, 30, TimeUnit.SECONDS, true, new EvalControlledCallable(evaluator.getEvalEngine()));
if (result != null) {
return printResultShortened(trimmedInput, result);
}
} catch (final AbortException re) {
// try {
return printResultShortened(trimmedInput, S.$Aborted);
// } catch (IOException e) {
// Validate.printException(buf, e);
// stderr.println(buf.toString());
// stderr.flush();
// return "";
// }
} catch (final FailedException re) {
// try {
return printResultShortened(trimmedInput, S.$Failed);
// } catch (IOException e) {
// Validate.printException(buf, e);
// stderr.println(buf.toString());
// stderr.flush();
// return "";
// }
} catch (final SyntaxError se) {
String msg = se.getMessage();
// stderr.flush();
return msg;
} catch (final RuntimeException re) {
Throwable me = re.getCause();
if (me instanceof MathException) {
Validate.printException(buf, me);
} else {
Validate.printException(buf, re);
}
// stderr.flush();
return "";
} catch (final Exception e) {
Validate.printException(buf, e);
// stderr.flush();
return "";
} catch (final OutOfMemoryError e) {
Validate.printException(buf, e);
// stderr.flush();
return "";
} catch (final StackOverflowError e) {
Validate.printException(buf, e);
// stderr.flush();
return "";
}
return buf.toString();
}
use of org.matheclipse.core.eval.exception.AbortException in project symja_android_library by axkr.
the class MathScriptEngine method eval.
@Override
public Object eval(final String script, final ScriptContext context) {
boolean relaxedSyntax = false;
final Object enableStackTraceBoolean = get("PRINT_STACKTRACE");
Level stackLogLevel = Boolean.TRUE.equals(enableStackTraceBoolean) ? Level.ERROR : Level.DEBUG;
try {
// first assign the EvalEngine to the current thread:
EvalEngine.setReset(fEngine);
// final Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
// ISymbol symbol;
// for (Map.Entry<String, Object> currEntry : bindings.entrySet()) {
// symbol = F.userSymbol(currEntry.getKey(), fEngine);
// symbol.pushLocalVariable(Object2Expr.convert(currEntry.getValue()));
// list.add(symbol);
// }
final Object decimalFormat = get("DECIMAL_FORMAT");
if (decimalFormat instanceof String) {
fDecimalFormat = (String) decimalFormat;
}
final Object relaxedSyntaxBoolean = get("RELAXED_SYNTAX");
if (Boolean.TRUE.equals(relaxedSyntaxBoolean)) {
relaxedSyntax = true;
fEngine.setRelaxedSyntax(relaxedSyntax);
}
boolean disableHistory = true;
final Object enableHistoryBoolean = get("ENABLE_HISTORY");
if (Boolean.TRUE.equals(enableHistoryBoolean)) {
disableHistory = false;
fEngine.setOutListDisabled(disableHistory, (short) 100);
}
// evaluate an expression
final Object stepwise = get("STEPWISE");
IExpr result;
String trimmedScript = script.trim();
if (trimmedScript.length() == 0) {
return "";
}
if (Boolean.TRUE.equals(stepwise)) {
result = fUtility.evalTrace(script, null);
} else {
result = fUtility.evaluate(script);
}
final Object returnType = context.getAttribute("RETURN_OBJECT");
if ((returnType != null) && returnType.equals(Boolean.TRUE)) {
// return the object "as is"
return result;
} else {
// return the object as String representation
if (result != null) {
return printResult(result, relaxedSyntax);
}
return "";
}
} catch (final AbortException e) {
LOGGER.log(stackLogLevel, "Aborted", e);
return printResult(S.$Aborted, relaxedSyntax);
} catch (final FailedException e) {
LOGGER.log(stackLogLevel, "Failed", e);
return printResult(S.$Failed, relaxedSyntax);
} catch (final MathException e) {
// catches parser errors as well
LOGGER.log(stackLogLevel, "evaluation failed", e);
return e.getMessage();
} catch (final ApfloatRuntimeException e) {
LOGGER.log(stackLogLevel, "ApFloat error", e);
// catch parser errors here
return "Apfloat: " + e.getMessage();
} catch (final Exception e) {
LOGGER.log(stackLogLevel, "Exception", e);
return "Exception: " + e.getMessage();
} catch (final OutOfMemoryError e) {
LOGGER.log(stackLogLevel, "Out of memory", e);
return "OutOfMemoryError";
} catch (final StackOverflowError e) {
LOGGER.log(stackLogLevel, "Stack overflow", e);
return "StackOverflowError";
} finally {
// if (list.size() > 0) {
// for (int i = 0; i < list.size(); i++) {
// list.get(i).popLocalVariable();
// }
// }
EvalEngine.remove();
}
}
Aggregations