Package javax.script

Examples of javax.script.Bindings


    //创建执行表达式
    String expression = buildExpression(transition, conditions);
   
    if(logger.isDebugEnabled())
      logger.debug("Transition Expressopn:{} Start", expression);
    Bindings variables= engine.createBindings();
    if(conditions != null) {
      for (Map.Entry<String, Object> m : conditions.entrySet()) {  
        variables.put(m.getKey(), m.getValue());
       
        if(logger.isDebugEnabled())
          logger.debug("    Transition Condition:{} = {}", m.getKey(), m.getValue());
      }
    }
View Full Code Here


  public Object eval(ScriptContext context) throws ScriptException {
    try {
      Map<String, Object> map = new HashMap<String, Object>();
      for (Iterator it = context.getScopes().iterator(); it.hasNext(); ) {
        int scope = ((Integer)it.next()).intValue();
        Bindings bindings = context.getBindings(scope);
        Set keys = bindings.keySet();
       
        for(Object key : keys) {
          map.put((String)key, bindings.get(key));
        }
        }
      return this.expression.execute(map);
      } catch (Exception e) {
        throw new ScriptException(e);
View Full Code Here

    languageId = scriptlanguage;
    logger.debug("the language id is " + scriptlanguage);

    ScriptEngineManager sm;
    ScriptEngine se;
    Bindings sb;
    try {
      sm = new ScriptEngineManager();
      se = sm.getEngineByName(getLanguageId());
      sb = se.getBindings(ScriptContext.ENGINE_SCOPE);
    }
View Full Code Here

            final ScriptEngine engine = scriptEngineManager.getEngineByExtension(languageExtension);
            if (engine == null) {
                resultLog.healthCheckError("No ScriptEngine available for extension {}", languageExtension);
            } else {
                // Set Bindings, with our ResultLog as a binding first, so that other bindings can use it
                final Bindings b = engine.createBindings();
                b.put(FormattingResultLog.class.getName(), resultLog);
                synchronized (bindingsValuesProviders) {
                    for(BindingsValuesProvider bvp : bindingsValuesProviders) {
                        log.debug("Adding Bindings provided by {}", bvp);
                        bvp.addBindings(b);
                    }
                }
                log.debug("All Bindings added: {}", b.keySet());

                final Object value = engine.eval(expression, b);
                if(value!=null && "true".equals(value.toString().toLowerCase())) {
                    resultLog.debug("Expression [{}] evaluates to true as expected", expression);
                } else {
View Full Code Here

        this.rootScope = rootScope;
    }

    public Object eval(Reader scriptReader, ScriptContext scriptContext)
            throws ScriptException {
        Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
        String scriptName = "NO_SCRIPT_NAME";
        {
            SlingScriptHelper helper = (SlingScriptHelper) bindings.get(SlingBindings.SLING);
            if (helper != null) {
                scriptName = helper.getScript().getScriptResource().getPath();
            }
        }

        // wrap the reader in an EspReader for ESP scripts
        if (scriptName.endsWith(RhinoJavaScriptEngineFactory.ESP_SCRIPT_EXTENSION)) {
            scriptReader = new EspReader(scriptReader);
        }

        // container for replaced properties
        Map<String, Object> replacedProperties = null;
        Scriptable scope = null;
        boolean isTopLevelCall = false;

        // create a rhino Context and execute the script
        try {

            final Context rhinoContext = Context.enter();
            rhinoContext.setOptimizationLevel(optimizationLevel());

            if (ScriptRuntime.hasTopCall(rhinoContext)) {
                // reuse the top scope if we are included
                scope = ScriptRuntime.getTopCallScope(rhinoContext);

            } else {
                // create the request top scope, use the ImporterToplevel here
                // to support the importPackage and importClasses functions
                scope = new ImporterTopLevel();

                // Set the global scope to be our prototype
                scope.setPrototype(rootScope);

                // We want "scope" to be a new top-level scope, so set its
                // parent scope to null. This means that any variables created
                // by assignments will be properties of "scope".
                scope.setParentScope(null);

                // setup the context for use
                WrapFactory wrapFactory = ((RhinoJavaScriptEngineFactory) getFactory()).getWrapFactory();
                rhinoContext.setWrapFactory(wrapFactory);

                // this is the top level call
                isTopLevelCall = true;
            }

            // add initial properties to the scope
            replacedProperties = setBoundProperties(scope, bindings);

            final int lineNumber = 1;
            final Object securityDomain = null;

            Object result = rhinoContext.evaluateReader(scope, scriptReader, scriptName,
                    lineNumber, securityDomain);

            if (result instanceof Wrapper) {
                result = ((Wrapper) result).unwrap();
            }

            return (result instanceof Undefined) ? null : result;

        } catch (JavaScriptException t) {

            // prevent variables to be pushed back in case of errors
            isTopLevelCall = false;

            final ScriptException se = new ScriptException(t.details(),
                t.sourceName(), t.lineNumber());

            // log the script stack trace
            ((Logger) bindings.get(SlingBindings.LOG)).error(t.getScriptStackTrace());

            // set the exception cause
            Object value = t.getValue();
            if (value != null) {
                if (value instanceof Wrapper) {
View Full Code Here

        }

        @Override
        public Object eval(final Reader script, final ScriptContext context)
                throws ScriptException {
            Bindings props = context.getBindings(ScriptContext.ENGINE_SCOPE);
            SlingScriptHelper scriptHelper = (SlingScriptHelper) props.get(SLING);
            if (scriptHelper != null) {

                // set the current class loader as the thread context loader for
                // the compilation and execution of the JSP script
                ClassLoader old = Thread.currentThread().getContextClassLoader();
View Full Code Here

    /**
     * @see org.apache.sling.api.scripting.SlingScript#call(org.apache.sling.api.scripting.SlingBindings, java.lang.String, java.lang.Object[])
     * @throws ScriptEvaluationException
     */
    public Object call(SlingBindings props, String method, Object... args) {
        Bindings bindings = null;
        Reader reader = null;
        boolean disposeScriptHelper = !props.containsKey(SLING);
        ResourceResolver oldResolver = null;
        try {
            bindings = verifySlingBindings(props);

            // use final variable for inner class!
            final Bindings b = bindings;
            // create script context
            final ScriptContext ctx = new ScriptContext() {

                private Bindings globalScope;
                private Bindings engineScope = b;
                private Writer writer = (Writer) b.get(OUT);
                private Writer errorWriter = new LogWriter((Logger) b.get(LOG));
                private Reader reader = (Reader)b.get(READER);
                private Bindings slingScope = new SimpleBindings();


                /**
                 * @see javax.script.ScriptContext#setBindings(javax.script.Bindings, int)
                 */
                public void setBindings(final Bindings bindings, final int scope) {
                    switch (scope) {
                        case SlingScriptConstants.SLING_SCOPE : this.slingScope = bindings;
                                                                break;
                        case 100: if (bindings == null) throw new NullPointerException("Bindings for ENGINE scope is null");
                                  this.engineScope = bindings;
                                  break;
                        case 200: this.globalScope = bindings;
                                  break;
                        default: throw new IllegalArgumentException("Invaild scope");
                    }
                }

                /**
                 * @see javax.script.ScriptContext#getBindings(int)
                 */
                public Bindings getBindings(final int scope) {
                    switch (scope) {
                        case SlingScriptConstants.SLING_SCOPE : return slingScope;
                        case 100: return this.engineScope;
                        case 200: return this.globalScope;
                    }
                    throw new IllegalArgumentException("Invaild scope");
                }

                /**
                 * @see javax.script.ScriptContext#setAttribute(java.lang.String, java.lang.Object, int)
                 */
                public void setAttribute(final String name, final Object value, final int scope) {
                    if (name == null) throw new IllegalArgumentException("Name is null");
                    final Bindings bindings = getBindings(scope);
                    if (bindings != null) {
                        bindings.put(name, value);
                    }
                }

                /**
                 * @see javax.script.ScriptContext#getAttribute(java.lang.String, int)
                 */
                public Object getAttribute(final String name, final int scope) {
                    if (name == null) throw new IllegalArgumentException("Name is null");
                    final Bindings bindings = getBindings(scope);
                    if (bindings != null) {
                        return bindings.get(name);
                    }
                    return null;
                }

                /**
                 * @see javax.script.ScriptContext#removeAttribute(java.lang.String, int)
                 */
                public Object removeAttribute(final String name, final int scope) {
                    if (name == null) throw new IllegalArgumentException("Name is null");
                    final Bindings bindings = getBindings(scope);
                    if (bindings != null) {
                        return bindings.remove(name);
                    }
                    return null;
                }

                /**
                 * @see javax.script.ScriptContext#getAttribute(java.lang.String)
                 */
                public Object getAttribute(String name) {
                    if (name == null) throw new IllegalArgumentException("Name is null");
                    for (final int scope : SCOPES) {
                        final Bindings bindings = getBindings(scope);
                        if ( bindings != null ) {
                            final Object o = bindings.get(name);
                            if ( o != null ) {
                                return o;
                            }
                        }
                    }
                    return null;
                }

                /**
                 * @see javax.script.ScriptContext#getAttributesScope(java.lang.String)
                 */
                public int getAttributesScope(String name) {
                    if (name == null) throw new IllegalArgumentException("Name is null");
                    for (final int scope : SCOPES) {
                       if ((getBindings(scope) != null) && (getBindings(scope).containsKey(name))) {
                           return scope;
                       }
                    }
                    return -1;
                }

                /**
                 * @see javax.script.ScriptContext#getScopes()
                 */
                public List<Integer> getScopes() {
                    return Arrays.asList(SCOPES);
                }

                /**
                 * @see javax.script.ScriptContext#getWriter()
                 */
                public Writer getWriter() {
                    return this.writer;
                }

                /**
                 * @see javax.script.ScriptContext#getErrorWriter()
                 */
                public Writer getErrorWriter() {
                    return this.errorWriter;
                }

                /**
                 * @see javax.script.ScriptContext#setWriter(java.io.Writer)
                 */
                public void setWriter(Writer writer) {
                    this.writer = writer;
                }

                /**
                 * @see javax.script.ScriptContext#setErrorWriter(java.io.Writer)
                 */
                public void setErrorWriter(Writer writer) {
                    this.errorWriter = writer;
                }

                /**
                 * @see javax.script.ScriptContext#getReader()
                 */
                public Reader getReader() {
                    return this.reader;
                }

                /**
                 * @see javax.script.ScriptContext#setReader(java.io.Reader)
                 */
                public void setReader(Reader reader) {
                    this.reader = reader;
                }
            };

            // set the current resource resolver if a request is available from the bindings
            if ( props.getRequest() != null ) {
                oldResolver = requestResourceResolver.get();
                requestResourceResolver.set(props.getRequest().getResourceResolver());
            }

            // set the script resource resolver as an attribute
            ctx.setAttribute(SlingScriptConstants.ATTR_SCRIPT_RESOURCE_RESOLVER,
                    this.scriptResource.getResourceResolver(), SlingScriptConstants.SLING_SCOPE);

            reader = getScriptReader();
            if ( method != null && !(this.scriptEngine instanceof Invocable)) {
                reader = getWrapperReader(reader, method, args);
            }

            // evaluate the script
            final Object result = scriptEngine.eval(reader, ctx);

            // call method - if supplied and script engine supports direct invocation
            if ( method != null && (this.scriptEngine instanceof Invocable)) {
                try {
                    ((Invocable)scriptEngine).invokeFunction(method, Arrays.asList(args).toArray());
                } catch (NoSuchMethodException e) {
                    throw new ScriptEvaluationException(this.scriptName, "Method " + method + " not found in script.", e);
                }
            }
            // optionall flush the output channel
            Object flushObject = bindings.get(FLUSH);
            if (flushObject instanceof Boolean && (Boolean) flushObject) {
                ctx.getWriter().flush();
            }

            // allways flush the error channel
            ctx.getErrorWriter().flush();

            return result;

        } catch (IOException ioe) {
            throw new ScriptEvaluationException(this.scriptName, ioe.getMessage(),
                ioe);

        } catch (ScriptException se) {
            Throwable cause = (se.getCause() == null) ? se : se.getCause();
            throw new ScriptEvaluationException(this.scriptName, se.getMessage(),
                cause);

        } finally {
            if ( props.getRequest() != null ) {
                requestResourceResolver.set(oldResolver);
            }

            // close the script reader (SLING-380)
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignore) {
                    // don't care
                }
            }

            // dispose of the SlingScriptHelper
            if ( bindings != null && disposeScriptHelper ) {
                final InternalScriptHelper helper = (InternalScriptHelper) bindings.get(SLING);
                if ( helper != null ) {
                    helper.cleanup();
                }
            }

View Full Code Here

        }
    }

    public Object eval(Reader script, ScriptContext scriptContext)
            throws ScriptException {
        Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);

        SlingScriptHelper helper = (SlingScriptHelper) bindings.get(SlingBindings.SLING);
        if (helper == null) {
            throw new ScriptException("SlingScriptHelper missing from bindings");
        }

        // ensure GET request
View Full Code Here

        };
    }

    private Bindings verifySlingBindings(final SlingBindings slingBindings) throws IOException {

      final Bindings bindings = new SimpleBindings();

        final SlingHttpServletRequest request = slingBindings.getRequest();

        // check sling object
        Object slingObject = slingBindings.get(SLING);
        if (slingObject == null) {

            if ( request != null ) {
                slingObject = new InternalScriptHelper(this.bundleContext, this, request, slingBindings.getResponse(), this.cache);
            } else {
                slingObject = new InternalScriptHelper(this.bundleContext, this, this.cache);
            }
        } else if (!(slingObject instanceof SlingScriptHelper) ) {
            throw fail(SLING, "Wrong type");
        }
        final SlingScriptHelper sling = (SlingScriptHelper)slingObject;
        bindings.put(SLING, sling);

        if (request != null) {
          final SlingHttpServletResponse response = slingBindings.getResponse();
            if (response == null) {
                throw fail(RESPONSE, "Missing or wrong type");
            }

            Object resourceObject = slingBindings.get(RESOURCE);
            if (resourceObject != null && !(resourceObject instanceof Resource)) {
                throw fail(RESOURCE, "Wrong type");
            }

            Object writerObject = slingBindings.get(OUT);
            if (writerObject != null && !(writerObject instanceof PrintWriter)) {
                throw fail(OUT, "Wrong type");
            }

            // if there is a provided sling script helper, check arguments
            if (slingBindings.get(SLING) != null) {

                if (sling.getRequest() != request) {
                    throw fail(REQUEST,
                        "Not the same as request field of SlingScriptHelper");
                }

                if (sling.getResponse() != response) {
                    throw fail(RESPONSE,
                        "Not the same as response field of SlingScriptHelper");
                }

                if (resourceObject != null
                    && sling.getRequest().getResource() != resourceObject) {
                    throw fail(RESOURCE,
                        "Not the same as resource of the SlingScriptHelper request");
                }

                if (writerObject != null
                    && sling.getResponse().getWriter() != writerObject) {
                    throw fail(OUT,
                        "Not the same as writer of the SlingScriptHelper response");
                }
            }

            // set base variables when executing inside a request
            bindings.put(REQUEST, sling.getRequest());
            bindings.put(READER, sling.getRequest().getReader());
            bindings.put(RESPONSE, sling.getResponse());
            bindings.put(RESOURCE, sling.getRequest().getResource());
            bindings.put(OUT, sling.getResponse().getWriter());
        }

        Object logObject = slingBindings.get(LOG);
        if (logObject == null) {
            logObject = LoggerFactory.getLogger(getLoggerName());
        } else if (!(logObject instanceof Logger)) {
            throw fail(LOG, "Wrong type");
        }
        bindings.put(LOG, logObject);

        // copy non-base variables
        for (Map.Entry<String, Object> entry : slingBindings.entrySet()) {
            if (!bindings.containsKey(entry.getKey())) {
                bindings.put(entry.getKey(), entry.getValue());
            }
        }

        if (!bindingsValuesProviders.isEmpty()) {
            Set<String> protectedKeys = new HashSet<String>();
View Full Code Here

public class RhinoJavaScriptEngineTest extends TestCase {

    public void testPreserveScopeBetweenEvals() throws ScriptException {
        MockRhinoJavaScriptEngineFactory factory = new MockRhinoJavaScriptEngineFactory();
        ScriptEngine engine = factory.getScriptEngine();
        Bindings context = new SimpleBindings();
        engine.eval("var f = 1", context);
        Object result = null;
        try {
            result = engine.eval("f += 1", context);
        } catch (ScriptException e) {
View Full Code Here

TOP

Related Classes of javax.script.Bindings

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.