public static void main(String[] args) { // Script Engine instantiation using ServiceProvider - this will // look in the classpath for a file // /META-INF/services/javax.script.ScriptEngineFactory // where the AbclScriptEngineFactory is registered ScriptEngine lispEngine = new ScriptEngineManager().getEngineByExtension("lisp"); // Alternatively, you can directly instantiate the script engine: // ScriptEngineManager scriptManager = new ScriptEngineManager(); // scriptManager.registerEngineExtension("lisp", new AbclScriptEngineFactory()); // ScriptEngine lispEngine = scriptManager.getEngineByExtension("lisp"); // (thanks to Peter Tsenter for suggesting this) // Accessing variables System.out.println(); System.out.println("*package* = " + lispEngine.get("*package*")); Object someValue = new Object(); lispEngine.put("someVariable", someValue); System.out.println("someVariable = " + lispEngine.get("someVariable")); try { // Interpretation (also from streams) lispEngine.eval("(defun hello (arg) (print (list arg someVariable)) (terpri))"); // Direct function invocation ((Invocable) lispEngine).invokeFunction("hello", "world"); // Implementing a Java interface in Lisp lispEngine.eval("(defun compare-to (&rest args) 42)"); Comparable c = ((Invocable) lispEngine).getInterface(java.lang.Comparable.class); System.out.println("compareTo: " + c.compareTo(null)); // Compilation! lispEngine.eval( "(defmacro slow-compiling-macro (arg) (dotimes (i 1000000) (incf i)) `(print ,arg))"); long millis = System.currentTimeMillis(); lispEngine.eval("(slow-compiling-macro 42)"); millis = System.currentTimeMillis() - millis; System.out.println("interpretation took " + millis); millis = System.currentTimeMillis(); CompiledScript cs = ((Compilable) lispEngine).compile("(slow-compiling-macro 42)"); millis = System.currentTimeMillis() - millis; System.out.println("compilation took " + millis); millis = System.currentTimeMillis(); cs.eval(); millis = System.currentTimeMillis() - millis; System.out.println("evaluation took " + millis); millis = System.currentTimeMillis(); cs.eval(); millis = System.currentTimeMillis() - millis; System.out.println("evaluation took " + millis); // Ecc. ecc. } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (ScriptException e) { e.printStackTrace(); } }
private void handleException(Realm realm, StackOverflowError e) { // Create script exception with stacktrace from stackoverflow-error. ScriptException exception = newInternalError(realm.defaultContext(), Messages.Key.StackOverflow); exception.setStackTrace(e.getStackTrace()); handleException(realm, exception); }
/** * Execute the script and return the ScriptResult corresponding. This method can add an additional * user bindings if needed. * * @param aBindings the additional user bindings to add if needed. Can be null or empty. * @param outputSink where the script output is printed to. * @param errorSink where the script error stream is printed to. * @return a ScriptResult object. */ public ScriptResult<E> execute( Map<String, Object> aBindings, PrintStream outputSink, PrintStream errorSink) { ScriptEngine engine = createScriptEngine(); if (engine == null) return new ScriptResult<>( new Exception("No Script Engine Found for name or extension " + scriptEngineLookup)); // SCHEDULING-1532: redirect script output to a buffer (keep the latest DEFAULT_OUTPUT_MAX_SIZE) BoundedStringWriter outputBoundedWriter = new BoundedStringWriter(outputSink, DEFAULT_OUTPUT_MAX_SIZE); BoundedStringWriter errorBoundedWriter = new BoundedStringWriter(errorSink, DEFAULT_OUTPUT_MAX_SIZE); engine.getContext().setWriter(new PrintWriter(outputBoundedWriter)); engine.getContext().setErrorWriter(new PrintWriter(errorBoundedWriter)); Reader closedInput = new Reader() { @Override public int read(char[] cbuf, int off, int len) throws IOException { throw new IOException("closed"); } @Override public void close() throws IOException {} }; engine.getContext().setReader(closedInput); engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName, ScriptContext.ENGINE_SCOPE); try { Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE); // add additional bindings if (aBindings != null) { for (Entry<String, Object> e : aBindings.entrySet()) { bindings.put(e.getKey(), e.getValue()); } } prepareBindings(bindings); Object evalResult = engine.eval(getReader()); engine.getContext().getErrorWriter().flush(); engine.getContext().getWriter().flush(); // Add output to the script result ScriptResult<E> result = this.getResult(evalResult, bindings); result.setOutput(outputBoundedWriter.toString()); return result; } catch (javax.script.ScriptException e) { // drop exception cause as it might not be serializable ScriptException scriptException = new ScriptException(e.getMessage()); scriptException.setStackTrace(e.getStackTrace()); return new ScriptResult<>(scriptException); } catch (Throwable t) { String stack = Throwables.getStackTraceAsString(t); if (t.getMessage() != null) { stack = t.getMessage() + System.lineSeparator() + stack; } return new ScriptResult<>(new Exception(stack)); } }
protected void fillRecipients(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { try { // to AddressTemplate to = getTemplate().getTo(); if (to != null) { fillRecipients(to, email, Message.RecipientType.TO, execution, session); } // cc AddressTemplate cc = getTemplate().getCc(); if (cc != null) { fillRecipients(cc, email, Message.RecipientType.CC, execution, session); } // bcc AddressTemplate bcc = getTemplate().getBcc(); if (bcc != null) { fillRecipients(bcc, email, Message.RecipientType.BCC, execution, session); } } catch (ScriptException e) { logger.error(e.getMessage(), e); } catch (RepositoryException e) { logger.error(e.getMessage(), e); } }
private boolean refresh(String importString) { this.scope = new Scope(new VariableList(), Parser.getExistingFunctionScope()); TreeMap imports = this.parser.getImports(); imports.clear(); if (importString.length() > 0) { String[] importList = importString.split(","); for (int i = 0; i < importList.length; ++i) { try { this.parser.importFile(importList[i], this.scope); } catch (ScriptException e) { // The user changed the script since it was validated KoLmafia.updateDisplay(MafiaState.ERROR, e.getMessage()); return false; } catch (Exception e) { StaticEntity.printStackTrace(e); return false; } } } this.lastImportString = importString; return true; }
private static void sendTransactionsToListener( StoredBlock block, NewBlockType blockType, BlockChainListener listener, int relativityOffset, List<Transaction> transactions, boolean clone, Set<Sha256Hash> falsePositives) throws VerificationException { for (Transaction tx : transactions) { try { if (listener.isTransactionRelevant(tx)) { falsePositives.remove(tx.getHash()); if (clone) tx = new Transaction(tx.params, tx.bitcoinSerialize()); listener.receiveFromBlock(tx, block, blockType, relativityOffset++); } } catch (ScriptException e) { // We don't want scripts we don't understand to break the block chain so just note that this // tx was // not scanned here and continue. log.warn("Failed to parse a script: " + e.toString()); } catch (ProtocolException e) { // Failed to duplicate tx, should never happen. throw new RuntimeException(e); } } }
/** Will load the script source from the provided filename. */ public static void loadScript(String script_name) { try { js_engine.eval(new java.io.FileReader(script_name)); } catch (ScriptException se) { se.printStackTrace(); } catch (java.io.IOException iox) { iox.printStackTrace(); } }
/** * Will invoke the "update" function of the script loaded by this engine with the provided list of * parameters. */ public static void executeScript(Object... args) { try { js_invocable.invokeFunction("update", args); } catch (ScriptException se) { se.printStackTrace(); } catch (NoSuchMethodException nsme) { nsme.printStackTrace(); } }
private void printScriptStackTrace(Realm realm, ScriptException e) { if (options.scriptStacktrace) { StringBuilder sb = new StringBuilder(); printScriptFrames(sb, realm, e, 1); if (sb.length() == 0 && e.getCause() != null) { printScriptFrames(sb, realm, e.getCause(), 1); } console.writer().print(sb.toString()); } }
/** Returns true if this output is to a key, or an address we have the keys for, in the wallet. */ public boolean isWatched(Wallet wallet) { try { Script script = getScriptPubKey(); return wallet.isWatchedScript(script); } catch (ScriptException e) { // Just means we didn't understand the output of this transaction: ignore it. log.debug("Could not parse tx output script: {}", e.toString()); return false; } }
private void preConfigure() { // Jython sys.path String dataPackDirForwardSlashes = SCRIPT_FOLDER.getPath().replaceAll("\\\\", "/"); String configScript = "import sys;sys.path.insert(0,'" + dataPackDirForwardSlashes + "');"; try { this.eval("jython", configScript); } catch (ScriptException e) { _log.fatal("Failed preconfiguring jython: " + e.getMessage()); } }
public void reportScriptFileError(File script, ScriptException e) { String dir = script.getParent(); String name = script.getName() + ".error.log"; if (dir != null) { File file = new File(dir + "/" + name); FileOutputStream fos = null; try { if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); String errorHeader = "Error on: " + file.getCanonicalPath() + "\r\nLine: " + e.getLineNumber() + " - Column: " + e.getColumnNumber() + "\r\n\r\n"; fos.write(errorHeader.getBytes()); fos.write(e.getMessage().getBytes()); _log.warn( "Failed executing script: " + script.getAbsolutePath() + ". See " + file.getName() + " for details."); } catch (IOException ioe) { _log.warn( "Failed executing script: " + script.getAbsolutePath() + "\r\n" + e.getMessage() + "Additionally failed when trying to write an error report on script directory. Reason: " + ioe.getMessage()); ioe.printStackTrace(); } finally { try { fos.close(); } catch (Exception e1) { } } } else { _log.warn( "Failed executing script: " + script.getAbsolutePath() + "\r\n" + e.getMessage() + "Additionally failed when trying to write an error report on script directory."); } }
@Test public void shouldMapScriptErrorCodeToLocalisedMessage() { // given ScriptException se; Locale locale = new Locale("te"); for (ScriptErrorCode errorCode : ScriptErrorCode.values()) { // when se = new ScriptException(errorCode); // then assertThat(se.getL10NMessage(locale)).isEqualTo(format(errorCode.name() + "-TRANSLATED")); } }
private void sendTransactionsToWallet( StoredBlock block, NewBlockType blockType, List<Transaction> newTransactions) throws VerificationException { // Scan the transactions to find out if any mention addresses we own. for (Transaction tx : newTransactions) { try { scanTransaction(block, tx, blockType); } catch (ScriptException e) { // We don't want scripts we don't understand to break the block chain, // so just note that this tx was not scanned here and continue. log.warn("Failed to parse a script: " + e.toString()); } } }
protected void fillContent(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { String text = getTemplate().getText(); String html = getTemplate().getHtml(); List<AttachmentTemplate> attachmentTemplates = getTemplate().getAttachmentTemplates(); try { if (html != null || !attachmentTemplates.isEmpty()) { // multipart MimeMultipart multipart = new MimeMultipart("related"); BodyPart p = new MimeBodyPart(); Multipart alternatives = new MimeMultipart("alternative"); p.setContent(alternatives, "multipart/alternative"); multipart.addBodyPart(p); // html if (html != null) { BodyPart htmlPart = new MimeBodyPart(); html = evaluateExpression(execution, html, session); htmlPart.setContent(html, "text/html; charset=UTF-8"); alternatives.addBodyPart(htmlPart); } // text if (text != null) { BodyPart textPart = new MimeBodyPart(); text = evaluateExpression(execution, text, session); textPart.setContent(text, "text/plain; charset=UTF-8"); alternatives.addBodyPart(textPart); } // attachments if (!attachmentTemplates.isEmpty()) { addAttachments(execution, multipart); } email.setContent(multipart); } else if (text != null) { // unipart text = evaluateExpression(execution, text, session); email.setText(text); } } catch (RepositoryException e) { logger.error(e.getMessage(), e); } catch (ScriptException e) { logger.error(e.getMessage(), e); } }
protected void fillSubject(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { String subject = getTemplate().getSubject(); if (subject != null) { try { String evaluatedSubject = evaluateExpression(execution, subject, session).replaceAll("[\r\n]", ""); email.setSubject(WordUtils.abbreviate(evaluatedSubject, 60, 74, "...")); } catch (RepositoryException e) { logger.error(e.getMessage(), e); } catch (ScriptException e) { logger.error(e.getMessage(), e); } } }
private void handleException(Realm realm, OutOfMemoryError e) { // Try to recover after OOM. Runtime rt = Runtime.getRuntime(); long beforeGc = rt.freeMemory(); rt.gc(); long afterGc = rt.freeMemory(); if (afterGc > beforeGc && (afterGc - beforeGc) < 50_000_000) { // Calling gc() cleared less than 50MB, assume unrecoverable OOM and rethrow error. throw e; } // Create script exception with stacktrace from oom-error. ScriptException exception = newInternalError(realm.defaultContext(), Messages.Key.OutOfMemoryVM); exception.setStackTrace(e.getStackTrace()); handleException(realm, exception); }
/** Returns true if any connected wallet considers any transaction in the block to be relevant. */ private boolean containsRelevantTransactions(Block block) { // Does not need to be locked. for (Transaction tx : block.transactions) { try { for (final ListenerRegistration<BlockChainListener> registration : listeners) { if (registration.executor != Threading.SAME_THREAD) continue; if (registration.listener.isTransactionRelevant(tx)) return true; } } catch (ScriptException e) { // We don't want scripts we don't understand to break the block chain so just note that this // tx was // not scanned here and continue. log.warn("Failed to parse a script: " + e.toString()); } } return false; }
@Test public void if_target_exception_set_cause() throws Exception { BugFreeBeanShell test = new BugFreeBeanShell() { @Override public void beanshellSetup() throws Exception { setBshFileName("src/test/resources/bsh/test3.bsh"); } }; test.setUp(); try { test.exec(); fail("A EvalError shall be trown!"); } catch (ScriptException x) { then(x.getCause()).isNotNull().isInstanceOf(NullPointerException.class); } }
/** Returns true if this output is to a key, or an address we have the keys for, in the wallet. */ public boolean isMine(Wallet wallet) { try { Script script = getScriptPubKey(); if (script.isSentToRawPubKey()) { byte[] pubkey = script.getPubKey(); return wallet.isPubKeyMine(pubkey); } if (script.isPayToScriptHash()) { return wallet.isPayToScriptHashMine(script.getPubKeyHash()); } else { byte[] pubkeyHash = script.getPubKeyHash(); return wallet.isPubKeyHashMine(pubkeyHash); } } catch (ScriptException e) { // Just means we didn't understand the output of this transaction: ignore it. log.debug("Could not parse tx output script: {}", e.toString()); return false; } }
/** * Fills the <code>from</code> attribute of the given email. The sender addresses are an optional * element in the mail template. If absent, each mail server supplies the current user's email * address. * * @see {@link InternetAddress#getLocalAddress(Session)} */ protected void fillFrom(Message email, Execution execution, JCRSessionWrapper session) throws MessagingException { try { AddressTemplate fromTemplate = getTemplate().getFrom(); // "from" attribute is optional if (fromTemplate == null) return; // resolve and parse addresses String addresses = fromTemplate.getAddresses(); if (addresses != null) { addresses = evaluateExpression(execution, addresses, session); // non-strict parsing applies to a list of mail addresses entered by a human email.addFrom(InternetAddress.parse(addresses, false)); } EnvironmentImpl environment = EnvironmentImpl.getCurrent(); IdentitySession identitySession = environment.get(IdentitySession.class); AddressResolver addressResolver = environment.get(AddressResolver.class); // resolve and tokenize users String userList = fromTemplate.getUsers(); if (userList != null) { String[] userIds = tokenizeActors(userList, execution, session); List<User> users = identitySession.findUsersById(userIds); email.addFrom(resolveAddresses(users, addressResolver)); } // resolve and tokenize groups String groupList = fromTemplate.getGroups(); if (groupList != null) { for (String groupId : tokenizeActors(groupList, execution, session)) { Group group = identitySession.findGroupById(groupId); email.addFrom(addressResolver.resolveAddresses(group)); } } } catch (ScriptException e) { logger.error(e.getMessage(), e); } catch (RepositoryException e) { logger.error(e.getMessage(), e); } }
@Test public void throw_parse_exception_if_script_has_errors() throws Exception { BugFreeBeanShell test = new BugFreeBeanShell() { @Override public void beanshellSetup() throws Exception { setBshFileName("src/test/resources/bsh/test1.bsh"); } }; test.setUp(); try { test.exec(); fail("A ScriptError shall be trown!"); } catch (Throwable x) { then(x).isInstanceOf(ScriptException.class); then(((ScriptException) x).getErrorLineNumber()).isEqualTo(6); then(((ScriptException) x).getErrorSourceFile()) .isEqualTo("src/test/resources/bsh/test1.bsh"); then(((ScriptException) x).getErrorText()).isEqualTo(")"); } }
@Test public void add_error_information() throws Exception { final String SCRIPT = "src/test/resources/bsh/test2.bsh"; BugFreeBeanShell test = new BugFreeBeanShell() { @Override public void beanshellSetup() throws Exception { setBshFileName(SCRIPT); } }; test.setUp(); try { test.exec(); fail("A EvalError shall be trown!"); } catch (ScriptException x) { then(x.getMessage()) .contains( String.format( "%s:%d at '%s'", "src/test/resources/bsh/test2.bsh", 5, "hello .prop ")); } }
private void handleException(Realm realm, ScriptException e) { String message = formatMessage("uncaught_exception", e.getMessage(realm.defaultContext())); console.printf("%s%n", message); printScriptStackTrace(realm, e); printStackTrace(e); }
@Test public void shouldMapScriptErrorCodeToMessage() { // given ScriptException se; // when se = new ScriptException(CONTEXT_NOT_RECOGNISED, context); // then assertThat(se.getMessage()).isEqualTo(format("Script type not recognised: {0}", context)); // when se = new ScriptException(LANGUAGE_NOT_SUPPORTED, language); // then assertThat(se.getMessage()) .isEqualTo(format("Scripting language not supported: {0}", language)); // when se = new ScriptException(FIND_BY_NAME_FAILED, scriptName, realm); // then assertThat(se.getMessage()) .isEqualTo(format("Failed to read script called {0} from realm {1}", scriptName, realm)); // when se = new ScriptException(FIND_BY_UUID_FAILED, uuid, realm); // then assertThat(se.getMessage()) .isEqualTo(format("Failed to read script with UUID {0} from realm " + "{1}", uuid, realm)); // when se = new ScriptException(DELETE_FAILED, uuid, realm); // then assertThat(se.getMessage()) .isEqualTo( format("Failed to delete script with UUID {0} from realm " + "{1}", uuid, realm)); // when se = new ScriptException(RETRIEVE_FAILED, uuid, realm); // then assertThat(se.getMessage()) .isEqualTo( format("Failed to retrieve script with UUID {0} from " + "realm {1}", uuid, realm)); // when se = new ScriptException(RETRIEVE_ALL_FAILED, realm); // then assertThat(se.getMessage()) .isEqualTo(format("Failed to retrieve scripts from realm {0}", realm)); // when se = new ScriptException(SAVE_FAILED, uuid, realm); // then assertThat(se.getMessage()) .isEqualTo(format("Failed to save script with UUID {0} in realm " + "{1}", uuid, realm)); // when se = new ScriptException(MISSING_SCRIPT_UUID); // then assertThat(se.getMessage()).isEqualTo("Script UUID must be specified"); // when se = new ScriptException(MISSING_SCRIPT_NAME); // then assertThat(se.getMessage()).isEqualTo("Script name must be specified"); // when se = new ScriptException(MISSING_SCRIPT); // then assertThat(se.getMessage()).isEqualTo("A script must be specified"); // when se = new ScriptException(MISSING_SCRIPTING_LANGUAGE); // then assertThat(se.getMessage()).isEqualTo("Scripting language must be specified"); // when se = new ScriptException(MISSING_SCRIPT_CONTEXT); // then assertThat(se.getMessage()).isEqualTo("Script type must be specified"); // when se = new ScriptException(SCRIPT_NAME_EXISTS, scriptName, realm); // then assertThat(se.getMessage()) .isEqualTo(format("Script with name {0} already exist in realm {1}", scriptName, realm)); // when se = new ScriptException(SCRIPT_UUID_EXISTS, uuid, realm); // then assertThat(se.getMessage()) .isEqualTo(format("Script with UUID {0} already exist in realm {1}", uuid, realm)); // when se = new ScriptException(SCRIPT_UUID_NOT_FOUND, uuid, realm); // then assertThat(se.getMessage()) .isEqualTo(format("Script with UUID {0} could not be found in realm {1}", uuid, realm)); // when se = new ScriptException(FILTER_BOOLEAN_LITERAL_FALSE); // then assertThat(se.getMessage()) .isEqualTo("The 'boolean literal' filter with value of 'false' is not supported"); // when se = new ScriptException(FILTER_EXTENDED_MATCH); // then assertThat(se.getMessage()).isEqualTo("The 'extended match' filter is not supported"); // when se = new ScriptException(FILTER_GREATER_THAN); // then assertThat(se.getMessage()).isEqualTo("The 'greater than' filter is not supported"); // when se = new ScriptException(FILTER_GREATER_THAN_OR_EQUAL); // then assertThat(se.getMessage()).isEqualTo("The 'greater than or equal' filter is not supported"); // when se = new ScriptException(FILTER_LESS_THAN); // then assertThat(se.getMessage()).isEqualTo("The 'less than' filter is not supported"); // when se = new ScriptException(FILTER_LESS_THAN_OR_EQUAL); // then assertThat(se.getMessage()).isEqualTo("The 'less than or equal' filter is not supported"); // when se = new ScriptException(FILTER_NOT); // then assertThat(se.getMessage()).isEqualTo("The 'not' filter is not supported"); // when se = new ScriptException(FILTER_PRESENT); // then assertThat(se.getMessage()).isEqualTo("The 'present' filter is not supported"); }