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(); } }
static void nashornInvokeMethod(String code) throws ScriptException, NoSuchMethodException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("nashorn"); engine.eval(code); Invocable inv = (Invocable) engine; JSObject propertiesDict = (JSObject) engine.get("properties"); Object result = null; Object property; long total = 0; for (int i = 0; i < RUNS; ++i) { long start = System.nanoTime(); for (int j = 0; j < BATCH; ++j) { property = propertiesDict.getMember("ssn"); result = inv.invokeMethod(property, "clean", "12345678"); } long stop = System.nanoTime(); System.out.println( "Run " + (i * BATCH + 1) + "-" + ((i + 1) * BATCH) + ": " + Math.round((stop - start) / BATCH / 1000) + " us"); total += (stop - start); } System.out.println("Average run: " + Math.round(total / RUNS / BATCH / 1000) + " us"); System.out.println( "Data is " + ((Invocable) engine).invokeMethod(result, "toString").toString()); }
@Override public ContainerResponse apply(final ContainerRequest requestContext) { final Object resource = routingContextFactory.get().peekMatchedResource(); final ProcessingContext processingCtx = invocationContextFactory.get(); if (method.isSuspendDeclared()) { processingCtx.setSuspendTimeout(method.getSuspendTimeout(), method.getSuspendTimeoutUnit()); } requestContext.setProperty(ReaderInterceptorExecutor.INTERCEPTORS, getReaderInterceptors()); requestContext.setProperty(WriterInterceptorExecutor.INTERCEPTORS, getWriterInterceptors()); final Response response = dispatcher.dispatch(resource, requestContext); if (method.isSuspendDeclared()) { processingCtx.setResponse(resource); processingCtx.trySuspend(); } final ContainerResponse responseContext = new ContainerResponse(requestContext, response); final Invocable invocable = method.getInvocable(); responseContext.setEntityAnnotations(invocable.getHandlingMethod().getDeclaredAnnotations()); if (responseContext.hasEntity() && !(responseContext.getEntityType() instanceof ParameterizedType)) { Type invocableType = invocable.getResponseType(); if (invocableType != null && Void.TYPE != invocableType && Void.class != invocableType && invocableType != Response.class) { responseContext.setEntityType(invocableType); } } return responseContext; }
/** * Mediation implementation when the script to be executed should be loaded from the registry * * @param synCtx the message context * @return script result * @throws ScriptException For any errors , when compile, run the script * @throws NoSuchMethodException If the function is not defined in the script */ private Object mediateWithExternalScript(MessageContext synCtx) throws ScriptException, NoSuchMethodException { prepareExternalScript(synCtx); ScriptMessageContext scriptMC = new ScriptMessageContext(synCtx, xmlHelper); processJSONPayload(synCtx, scriptMC); return invocableScript.invokeFunction(function, new Object[] {scriptMC}); }
@Test public void getInterface() throws ScriptException { engine.eval("calculate <- function(x) sqrt(x)"); Calculator calculator = invocableEngine.getInterface(Calculator.class); assertThat(calculator.calculate(64), equalTo(8d)); }
@Test public void invokeMethod() throws ScriptException, NoSuchMethodException { Object obj = engine.eval("list(execute=sqrt)"); DoubleVector result = (DoubleVector) invocableEngine.invokeMethod(obj, "execute", 16); assertThat(result.length(), equalTo(1)); assertThat(result.get(0), equalTo(4d)); }
@Test public void invokeFunction() throws ScriptException, NoSuchMethodException { engine.eval("f <- function(x) sqrt(x)"); DoubleVector result = (DoubleVector) invocableEngine.invokeFunction("f", 4); assertThat(result.length(), equalTo(1)); assertThat(result.get(0), equalTo(2d)); }
/** * 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 Invocable createInvocable() { assert handlerClass != null || handlerInstance != null; final MethodHandler handler; if (handlerClass != null) { handler = MethodHandler.create(handlerClass, encodedParams); } else { // instance based handler = MethodHandler.create(handlerInstance); } return Invocable.create(handler, handlingMethod, encodedParams); }
@Override public void visitInvocable(final Invocable invocable) { // TODO: check invocable. Class resClass = invocable.getHandler().getHandlerClass(); if (resClass != null && !checkedClasses.contains(resClass)) { checkedClasses.add(resClass); final boolean provider = Providers.isProvider(resClass); int counter = 0; for (Annotation annotation : resClass.getAnnotations()) { if (SCOPE_ANNOTATIONS.contains(annotation.annotationType())) { counter++; } } if (counter == 0 && provider) { Errors.warning( resClass, LocalizationMessages.RESOURCE_IMPLEMENTS_PROVIDER( resClass, Providers.getProviderContracts(resClass))); } else if (counter > 1) { Errors.fatal(resClass, LocalizationMessages.RESOURCE_MULTIPLE_SCOPE_ANNOTATIONS(resClass)); } } }
private ResourceMethodInvoker( Provider<RoutingContext> routingContextFactory, Provider<ProcessingContext> invocationContextFactory, ResourceMethodDispatcher.Provider dispatcherProvider, ResourceMethodInvocationHandlerProvider invocationHandlerProvider, ResourceMethod method, MultivaluedMap<Class<? extends Annotation>, ContainerRequestFilter> nameBoundRequestFilters, MultivaluedMap<Class<? extends Annotation>, ContainerResponseFilter> nameBoundResponseFilters, Collection<ReaderInterceptor> globalReaderInterceptors, Collection<WriterInterceptor> globalWriterInterceptors, MultivaluedMap<Class<? extends Annotation>, ReaderInterceptor> nameBoundReaderInterceptors, MultivaluedMap<Class<? extends Annotation>, WriterInterceptor> nameBoundWriterInterceptors, Collection<DynamicBinder> dynamicBinders) { this.routingContextFactory = routingContextFactory; this.invocationContextFactory = invocationContextFactory; this.method = method; final Invocable invocable = method.getInvocable(); this.dispatcher = dispatcherProvider.create(invocable, invocationHandlerProvider.create(invocable)); this.resourceMethod = invocable.getHandlingMethod(); this.resourceClass = invocable.getHandler().getHandlerClass(); List<ReaderInterceptor> _readerInterceptors = new LinkedList<ReaderInterceptor>(); List<WriterInterceptor> _writerInterceptors = new LinkedList<WriterInterceptor>(); for (DynamicBinder dynamicBinder : dynamicBinders) { Object boundProvider = dynamicBinder.getBoundProvider(this); // TODO: should be based on the type arg. value rather than instanceof? if (boundProvider instanceof WriterInterceptor) { _writerInterceptors.add((WriterInterceptor) boundProvider); } if (boundProvider instanceof ReaderInterceptor) { _readerInterceptors.add((ReaderInterceptor) boundProvider); } if (boundProvider instanceof ContainerRequestFilter) { this.requestFilters.add((ContainerRequestFilter) boundProvider); } if (boundProvider instanceof ContainerResponseFilter) { this.responseFilters.add((ContainerResponseFilter) boundProvider); } } _readerInterceptors.addAll(globalReaderInterceptors); _writerInterceptors.addAll(globalWriterInterceptors); if (resourceMethod != null) { addNameBoundFiltersAndInterceptors( nameBoundRequestFilters, nameBoundResponseFilters, nameBoundReaderInterceptors, nameBoundWriterInterceptors, this.requestFilters, this.responseFilters, _readerInterceptors, _writerInterceptors, method); } Collections.sort( _readerInterceptors, new PriorityComparator<ReaderInterceptor>(PriorityComparator.Order.ASCENDING)); Collections.sort( _writerInterceptors, new PriorityComparator<WriterInterceptor>(PriorityComparator.Order.ASCENDING)); this.readerInterceptors = Collections.unmodifiableList(_readerInterceptors); this.writerInterceptors = Collections.unmodifiableList(_writerInterceptors); }